2

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?

Pikachu
  • 309
  • 4
  • 14

2 Answers2

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.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
-1

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"}'
sattva_venu
  • 677
  • 8
  • 22
  • He specifically asked to have custom field names when serializing. – Daan May 02 '22 at 15:16
  • @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. – sattva_venu May 18 '22 at 17:35