I use:
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)
but get an error:
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
I follow the steps which instructs to unpickle a Json obj to a Python obj, just like this:
json_str = '{"age": 20, "score": 88, "name": "Bob"}'
print(json.loads(json_str, object_hook=dict2student))
Why can't it take effect on a dict? How can I revise?
object_hook, you don't really need it.return dict(**d), but it is redundant becausejson.loadsautomatically converts your json to a dictionary.