我使用json库来解码json文本
import json
我有一个像这样定义的 Party 类:
class Party(object):
id = ""
code = ""
create_date = ""
citizenship = ""
object_hook 方法:
def as_party(d):
p = Party()
p.__dict__.update(d)
return p
我可以使用此方法从 json 文本中获取 Party 对象:
def parse_as(s, typo_class):
return json.loads(str(s), object_hook=typo_class)
当我对包含编码的 Party 类的 json 文本调用 parse_as 方法时,我得到一个 Party 类型的对象。
json_text = {'id': 2, 'code': '2', 'create_date': null, 'citizenship': null}
party1 = parse_as(json_text, as_party)
我可以这样调用它的属性:
print party1.code
我的问题是让 parse_as 方法能够解析包含像这样的 Party 对象列表的 json 文本:
json_text = [{'id': 2, 'code': '2', 'create_date': null, 'citizenship': null}, {'id': 5, 'code': '3', 'create_date': null, 'citizenship': null}, {'id': 6, 'code': '8', 'create_date': null, 'citizenship': null}]
请帮助我并提前致谢!
最佳答案
需要更改对象 Hook
def as_party(d):
if isinstance(d, dict):
p = Party()
p.__dict__.update(d)
elif isinstance(d, list):
out = []
for i in d:
n = Party()
n.__dict__.update(i)
out.append(n)
p = out
else:
raise Exception('got non-dict value %s' % d)
return p
顺便说一句,我不会使用 __dict__
,而是使用带有一些前缀的 setattr...
因为如果键值是 python 关键字,那就不好了。
>>> a = Foo()
>>> a.__dict__['except'] = 1
>>> a.except
File "<stdin>", line 1
a.except
^
SyntaxError: invalid syntax
关于python - 如何从Python中的json文本解析类对象列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25554666/