0

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?

2
  • 1
    Remove the object_hook, you don't really need it. Commented Aug 2, 2017 at 15:37
  • 1
    Alternatively, you can use return dict(**d), but it is redundant because json.loads automatically converts your json to a dictionary. Commented Aug 2, 2017 at 15:38

2 Answers 2

2

Once you load json using d = json.loads(json_str) d is python dict you cannot get the item using .(dot).

You need:

json_str = '{"name":"Saeron", "age":23, "score":100}'
d = json.loads(json_str)
print(d['name'])
Sign up to request clarification or add additional context in comments.

Comments

2

json.loads can evaluate your string as a Python dictionary directly as follows:

json_str = '{"name":"Saeron", "age":23, "score":100}'
d = json.loads(json_str)
print(d['name'])
>>>Saeron

The function you pass via the object_hook parameter will receive the dictionary that was created from the given string as input

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.