2017-04-17 52 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%同意