我用:
json_str = '{"name":"Saeron", "age":23, "score":100}'
def json2dict(d):
return dict(d['name'],d['age'],d['score'])
d = json.loads(json_str, object_hook=json2dict)
print(d.name)
但是收到错误:
Traceback (most recent call last):
File "C:/Users/40471/PycharmProjects/untitled/untitled.py", line 693, in <module>
d = json.loads(json_str, object_hook=json2dict)
File "C:\Program Files\Python36\lib\json\__init__.py", line 367, in loads
return cls(**kw).decode(s)
File "C:\Program Files\Python36\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Program Files\Python36\lib\json\decoder.py", line 355, in raw_decode
obj, end = self.scan_once(s, idx)
File "C:/Users/40471/PycharmProjects/untitled/untitled.py", line 692, in json2dict
return dict(d['name'],d['age'],d['score'])
TypeError: dict expected at most 1 arguments, got 3
我按照指示将Json obj解开为Python obj的步骤,就像这样:
json_str = '{"age": 20, "score": 88, "name": "Bob"}'
print(json.loads(json_str, object_hook=dict2student))
为什么它不会对字典生效?我怎么修改?
答案 0 :(得分:2)
使用d = json.loads(json_str)
加载json后,d是python dict
你无法使用。(点)。
你需要:
json_str = '{"name":"Saeron", "age":23, "score":100}'
d = json.loads(json_str)
print(d['name'])
答案 1 :(得分:2)
json.loads可以直接将您的字符串评估为Python字典,如下所示:
json_str = '{"name":"Saeron", "age":23, "score":100}'
d = json.loads(json_str)
print(d['name'])
>>>Saeron
通过object_hook参数传递的函数将接收从给定字符串创建的字典作为输入