简体   繁体   English

如何使用python中的自定义字段将对象序列化为json

[英]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.我想将对象序列化为 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.我想用我自己的字段将我的对象序列化为 json。 Instead of 'person_age' - 'age'.而不是'person_age' - 'age'。 Instead of 'person_name' - 'name':而不是 'person_name' - 'name':

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

How can this be done if the class has many fields?如果类有很多字段,如何做到这一点?

IIUC, you could do the following: IIUC,您可以执行以下操作:

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.注意你只需要那些你想改变的名字,在上面的例子中weight保持不变。

You can use json module to serialize the object to json format.您可以使用 json 模块将对象序列化为 json 格式。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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