我正在尝试将json
字符串转换为model
然后使用.
我已查看another question
但不同,我的json sting看起来像,
{
"id":"123",
"name":"name",
"key":{
"id":"345",
"des":"des"
},
}
我更喜欢使用2类,
class A:
id = ''
name = ''
key = new B()
class B:
id = ''
des = ''
答案 0 :(得分:2)
很少有图书馆可以提供帮助:
对于更简单的情况,您也可以使用标准库中的内容,例如
答案 1 :(得分:1)
为此,您应该将自定义回调作为object_hook
函数的json.loads
参数提供。
object_hook
是一个可选函数,将使用 任何对象文字解码的结果(dict
)。的返回值 将使用object_hook
代替dict
。此功能 可用于实现自定义解码器(例如JSON-RPC类提示)。
答案 2 :(得分:1)
考虑使用collections.namestuple子类:
json_str = '''
{
"id":"123",
"name":"name",
"key":{
"id":"345",
"des":"des"
}
}'''
B = collections.namedtuple('B', 'id des')
A = collections.namedtuple('A', 'id name key')
def make_models(o):
if 'key' in o:
return A(o['id'], o['name'], B(id=o['key']['id'], des=o['key']['des']))
else:
return o
result = json.loads(json_str, object_hook=make_models)
print(type(result)) # outputs: <class '__main__.A'>
print(result.id) # outputs: 123
print(result.key.id) # outputs: 345