3

I have a class

class Person(object):
    def __init__(self,age,name):
        self.person_age = age
        self.person_name = name

And i want to serialize object to json. I can do so:

person = Person(20,'Piter')
person.__dict__

But such an approach will return it:

{'person_age':20,person_name:'Piter'}

I want serialize my object to json with my own fields. Instead of 'person_age' - 'age'. Instead of 'person_name' - 'name':

{'age':20,name:'Piter'}

How can this be done if the class has many fields?

10
  • Why are you adding the 'person_' to your fields? Commented Mar 21, 2020 at 15:12
  • This is just an example :) Commented Mar 21, 2020 at 15:13
  • Use DRF Serializers Commented Mar 21, 2020 at 15:13
  • So you have a mapping of object fields to json fields? Something like {'person_name' : 'name', 'person_age':'age'}? Commented Mar 21, 2020 at 15:14
  • You could look into jsonpickle. stackoverflow.com/a/8614096 Commented Mar 21, 2020 at 15:15

2 Answers 2

5

IIUC, you could do the following:

import json


class Person(object):
    def __init__(self, age, name, weight):
        self.person_age = age
        self.person_name = name
        self.weight = weight


p = Person(30, 'Peter', 78)
mapping = {'person_age': 'age', 'person_name': 'name'}
result = json.dumps({mapping.get(k, k): v for k, v in p.__dict__.items()})

print(result)

Output

{"age": 30, "name": "Peter", "weight": 78}

Note that you only need those names you want to change, in the example above weight remains unchanged.

Sign up to request clarification or add additional context in comments.

Comments

-2

You can use json module to serialize the object to json format.

Here is the example:-

import json
class Person(object):
    def __init__(self,age,name):
        self.person_age = age
        self.person_name = name

person = Person(20,'Piter')

person_JSON = json.dumps(person.__dict__)
print(person_JSON)

Output:-

'{"person_age": 20, "person_name": "Piter"}'

3 Comments

He specifically asked to have custom field names when serializing.
@Daan, nin hendran I have written the code with respect to the question asked. Let me know what exactly is the issue you saw with my code.
Second part - "I want serialize my object to json with my own fields. Instead of 'person_age' - 'age'. Instead of 'person_name' - 'name':"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.