0
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
我遵循的指示unpickle一個JSON obj轉換爲一個Python obj中的步驟,就像這樣:
json_str = '{"age": 20, "score": 88, "name": "Bob"}'
print(json.loads(json_str, object_hook=dict2student))
爲什麼不能在字典中生效?我該如何修改?
刪除'object_hook',你並不需要它。 –
或者,您可以使用'return dict(** d)',但它是多餘的,因爲'json.loads'會自動將您的json轉換爲字典。 –