2017-08-02 107 views
0

我使用:如何將JSON對象轉換爲Python對象?

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)) 

爲什麼不能在字典中生效?我該如何修改?

+1

刪除'object_hook',你並不需要它。 –

+1

或者,您可以使用'return dict(** d)',但它是多餘的,因爲'json.loads'會自動將您的json轉換爲字典。 –

回答

2

一旦您使用d = json.loads(json_str)加載json d是python字典 您無法使用。(點)獲取該項目。

您需要:

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

json.loads可以直接評估你的字符串作爲一個Python解釋如下:

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

您通過object_hook參數傳入通過該功能將收到這是字典從給定的字符串創建輸入