简体   繁体   中英

How to serialize object to json with custom fields in python

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?

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.

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"}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM