[英]Python JSON serialization for nested object
我有數據庫記錄的列表,我想將此作為JSON返回給客戶端。 記錄是Employee對象的類型,應根據薪水進行分組。
我已經完成了對這些記錄的分組。 但是我無法生成首選的JSON格式。
“ SalaryEmployeeList”對象不可JSON序列化。
這里的問題是“薪水”和“ employee_list”標記丟失。
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
必需的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
}
]
}
}
如前所述,您將需要實現自己的序列化邏輯。 此外,希望以下代碼對您有所幫助:
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.