2017-04-17 53 views
-2

在一個項目上工作,這是推動我堅果,我在網上搜索,發現有幾個答案,爲我的其他查詢是json相關的工作,但這一個它的一個噩夢位不斷收到TrackStack錯誤無法從多個值獲取一個值json python

這是我的JSON

ServerReturnJson = { 
    "personId":"59c16cab-9f28-454e-8c7c-213ac6711dfc", 
    "persistedFaceIds":["3aaafe27-9013-40ae-8e2a-5803dad90d04"], 
    "name":"ramsey,", 
    "userData":null 
} 

data = responseIdentify.read() 
print("The following data return : " + data) 

#Parse json data to print just 

load = json.loads(data) 

print(load[0]['name']) 

和多數民衆贊成在我的問題是我無法獲取的價值形式的名稱,嘗試下面的語句,然後我得到這個錯誤:

Traceback (most recent call last): 
    File "C:\Python-Windows\random_test\cogT2.py", line 110, in <module> 
    for b in load[0]['name']: 
KeyError: 0 

使用for循環

for b in load[0]['name']: 
    print b[load] 

任何支持將是最受歡迎的敢肯定它的簡單的東西只是不明白。

+0

您顯示的數據不是一個列表,因此不會有'0'索引。你不顯示你想得到的東西,我根本沒有理由爲''for'循環。 –

+0

print的輸出是什麼(「以下數據返回:」+數據)? – Shiping

回答

0

瞭解如何在JSON中引用嵌套字典和列表是最困難的部分。這裏有幾件事要考慮。

使用原始數據

ServerReturnJson = { 
    "personId":"59c16cab-9f28-454e-8c7c-213ac6711dfc", 
    "persistedFaceIds":["3aaafe27-9013-40ae-8e2a-5803dad90d04"], 
    "name":"ramsey,", 
    "userData":'null' 
} 

# No index here, just the dictionary key 
print(ServerReturnJson['name']) 

通過使類型的字典

ServerReturnJson = [{ 
    "personId":"59c16cab-9f28-454e-8c7c-213ac6711dfc", 
    "persistedFaceIds":["3aaafe27-9013-40ae-8e2a-5803dad90d04"], 
    "name":"ramsey", 
    "userData": 'null' 
}, 
    { 
     "personId": "234123412341234234", 
     "persistedFaceIds": ["1241234123423"], 
     "name": "miller", 
     "userData": 'null' 
    } 
] 

# You can use the index here since you have a list of dictionaries 
print(ServerReturnJson[1]['name']) 

# You can iterate like this 
for item in ServerReturnJson: 
    print(item['name']) 
0

感謝您的支持基本上是微軟面對的API返回回JSON沒有指數像克里斯說的列表中所增加第二人這第一個例子

上面的例子只有在添加以下內容時纔有效 data = responseIdentify.read()#read incoming resp OND表格服務器 ServerReturnJson = json.loads(數據)

所以完整的答案如下:

dataJson= { 
    "personId":"59c16cab-9f28-454e-8c7c-213ac6711dfc", 
    "persistedFaceIds":["3aaafe27-9013-40ae-8e2a-5803dad90d04"], 
    "name":"ramsey,", 
    "userData":'null' 
    } 
    # add json load here 
    ServerReturnJson = json.loads(dataJson) 
    # No index here, just the dictionary key 
    print(ServerReturnJson['name']) 

學分克里斯感謝,最後一件事克里斯提「瞭解如何引用嵌套的字典和列表在JSON中是最難的部分「100%同意