Json序列化python
我有员工类,其中有姓名年龄和地址列表,其中包含员工的地址列表 我的代码设计如下Json序列化python,python,json,Python,Json,我有员工类,其中有姓名年龄和地址列表,其中包含员工的地址列表 我的代码设计如下 class Employee: Name='' Age ='' Addresses =[] class Address: State ='' District ='' City='' adress1 =Address(); adress1.State='West bengal' adress1.District ='Jalpaiguri' adress1.City= 'Ko
class Employee:
Name=''
Age =''
Addresses =[]
class Address:
State =''
District =''
City=''
adress1 =Address();
adress1.State='West bengal'
adress1.District ='Jalpaiguri'
adress1.City= 'Kolkata'
adress2 =Address()
adress2.State='West Bengal'
adress2.District ='Darjeeling'
adress2.City= 'Siliguri'
employee =Employee()
employee.name ='Gunjan'
employee.age =22
employee.Addresses.append(adress1)
employee.Addresses.append(adress2)
我想将employee转换为json表示。我试过了
json.dumps(employee.__dict__).
但这只提供了员工的姓名和年龄属性,而没有提供其中包含的地址列表
如果有人能指导我获得像这样完美的json表示,那将是非常有帮助的-
{“姓名”:“Gunjan”,“年龄”:“22”,“地址”:[{“州”:“西孟加拉邦”,“市”:“西里古里”,“区”:“大吉岭”},{“州”:“西孟加拉邦”,“市”:“加尔各答”,“区”:“新贾尔巴古里”}]
谢谢几件事,python中类成员的约定是小写的 另一个问题是,您调用了emplyee.name,而您的成员是name 如果您想在类中使用数据成员,您应该编写self.name,例如 正如您所看到的,我实现了dump函数,如果一个类有一个对象列表,这是一个问题,我不知道任何简单的解决方案 我为您编写了符合您意图的代码
import json
class Employee:
def __init__(self):
self.name=''
self.age =''
self.addresses =[]
def dump(self):
return {"Name": self.name,
"Age": self.age,
"Addresses": [addr.__dict__ for addr in self.addresses]}
class Address:
def __init__(self):
self.state =''
self.district =''
self.city=''
adress1 =Address()
adress1.state='West bengal'
adress1.district ='Jalpaiguri'
adress1.city= 'Kolkata'
adress2 =Address()
adress2.state='West Bengal'
adress2.district ='Darjeeling'
adress2.city= 'Siliguri'
employee =Employee()
employee.name ='Gunjan'
employee.age =22
employee.addresses.append(adress1)
employee.addresses.append(adress2)
print json.dumps(employee.dump())
结果:
{"Age": 22, "Name": "Gunjan", "Addresses": [{"City": "", "State": "", "District": ""}, {"City": "Siliguri", "State": "West Bengal", "District": "Darjeeling"}]}
事实上,您正在尝试创建一个可以转换为JSON的字典,而不是直接创建JSON表示(Python允许这两种技术) 要创建字典,请尝试以下操作:
class Employee(object):
def __init__(self, name, age):
self.name = name
self.age = age
self.addresses = []
@property
def __dict__(self):
return {
"name": self.name,
"age": self.age,
"addresses": [addr.__dict__ for addr in self.addresses]
}
class Address(object):
def __init__(self, state, district, city):
self.state = state
self.district = district
self.city = city
employee = Employee("Gunjan", 22)
employee.addresses.append(Address("West Bengal", "Jalpaiguri", "Kolkata"))
employee.addresses.append(Address("West Bengal", "Darjeeling", "Siliguri"))
print employee.__dict__
应打印:
{'age': 22, 'name': 'Gunjan', 'addresses': [{'city': 'Kolkata', 'state': 'West Bengal', 'district': 'Jalpaiguri'}, {'city': 'Siliguri', 'state': 'West Bengal', 'district': 'Darjeeling'}]}
也许这会有帮助