[英]Python JSON serialization for nested object
I have list of database records and I want to return this as JSON to the client. 我有数据库记录的列表,我想将此作为JSON返回给客户端。 The records are type of Employee object and should be grouped based on salary. 记录是Employee对象的类型,应根据薪水进行分组。
I have completed grouping this records. 我已经完成了对这些记录的分组。 But I am not able to generate the preferred JSON format. 但是我无法生成首选的JSON格式。
"SalaryEmployeeList" object is not JSON serializable. “ SalaryEmployeeList”对象不可JSON序列化。
Here the problem is "salary" and "employee_list" tag is missing. 这里的问题是“薪水”和“ employee_list”标记丢失。
Python Objects: Python对象:
class Employee:
def __init__(self, id, name, salary):
self.id = id
self.name = name
self.salary = salary
def toJson(self):
return json.dumps(self, default=lambda o: o.__dict__,
sort_keys=True, indent=4)
def __repr__(self):
self.toJson()
class SalaryEmployeeList:
def __init__(self, salary, employee_list):
self.salary = salary
self.employee_list = employee_list
def toJson(self):
return json.dumps(self, default=lambda o: o.__dict__,
sort_keys=True, indent=4)
def __repr__(self):
self.toJson()
1 Abi 5000
2 Bal 6000
3 Con 8000
4 Den 5000
5 Eon 6000
6 Fun 8000
7 Gop 5000
8 Han 6000
9 Iyo 8000
10 John 5000
11 Kami 6000
Required JSON format 必需的JSON格式
{
{
"salary": 5000,
"employee_list": [
{
"name": "Abi",
"id": 1
},
{
"name": "Den",
"id": 4
},
{
"name": "Gop",
"id": 7
},
{
"name": "John",
"id": 10
}
]
},
{
"salary": 6000,
"employee_list": [
{
"name": "Bal",
"id": 2
},
{
"name": "Eon",
"id": 5
},
{
"name": "Han",
"id": 8
},
{
"name": "Kami",
"id": 11
}
]
},
{
"salary": 8000,
"employee_list": [
{
"name": "Con",
"id": 3
},
{
"name": "Fun",
"id": 6
},
{
"name": "Iyo",
"id": 9
}
]
}
}
As mentioned before, you will need to implement your own serialization logic. 如前所述,您将需要实现自己的序列化逻辑。 Furthermore, I hope the following code helps: 此外,希望以下代码对您有所帮助:
class Employee:
def __init__(self, id, name, salary):
self.id = id
self.name = name
self.salary = salary
def toJson(self):
return json.dumps({'name': self.name, 'salary': self.salary}, sort_keys=True, indent=4)
def __repr__(self):
return self.toJson()
class SalaryEmployeeList:
def __init__(self, salary, employee_list):
self.salary = salary
self.employee_list = employee_list
def toJson(self):
return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4)
def __repr__(self):
return self.toJson()
if __name__ == '__main__':
a = Employee(1, 'alice', 1000)
b = Employee(2, 'bob', 2000)
c = Employee(3, 'carl', 3000)
employee_list = SalaryEmployeeList(0, [a, b, c])
json_dictionary = json.loads(employee_list.toJson()) # dictionary loaded from JSON string
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.