解析嵌套的JSON响应Python [英] Parsing nested JSON response Python
问题描述
整个周末我都被困住了,有人可以帮我吗?
I've been stuck on this all weekend, can anybody help me out please?
我正在尝试解析嵌套的JSON响应.我似乎无法返回我需要的值,每当我尝试解析它时,我都会得到关于字符串索引必须为整数"的错误.
I'm trying to parse a nested JSON response. I cannot seem to return the values I need, I just get errors about "string indices must be integers" whenever I try to parse it...
我想要实现的是:对于JSON中的每个对象,请提取available_projects,然后从每个对象中提取available_models.例如,第一个应该是:model001,model_20171004-090552.
What I am trying to achieve is: for each object in the JSON, extract the available_projects, and then the available_models from each. For example, the first one should be: model001, model_20171004-090552.
示例JSON响应:
{
"available_projects": {
"model001": {
"available_models": [
"model_20171004-090552"
],
"status": "ready"
},
"model002": {
"available_models": [
"model_20171013-143108"
],
"status": "ready"
},
"model002b": {
"available_models": [
"model_20171013-151458"
],
"status": "ready"
}
}
我的代码:
myText = requests.get('http://localhost:5000/status')
jsonresponse = json.loads(myText.text)
for element in jsonresponse[u'available_projects']:
for AM in element[u'available_models']: ## this gives me the errors..
print AM
如果我只是执行针对jsonresponse [u'available_projects']中的元素:print元素"的语句,它将正确打印出available_projects列表.我该如何使用该输出来更深入地研究JSON?
if I just do a "for element in jsonresponse[u'available_projects']: print element" statement, it correctly prints the available_projects list. How can I use that output to delve one level deeper into the JSON?
任何帮助,或者代码片段都很棒-谢谢!!
Any help, or a code snippet would be amazing - thank you!!
推荐答案
您可以使用 键方法 ,以获取键,然后进行迭代以获取所需的值.
You can use the keys method in the dictionary object to fetch the keys and then iterate over to get the required value.
示例:
d = {
"available_projects": {
"model001": {
"available_models": [
"model_20171004-090552"
],
"status": "ready"
},
"model002": {
"available_models": [
"model_20171013-143108"
],
"status": "ready"
},
"model002b": {
"available_models": [
"model_20171013-151458"
],
"status": "ready"
}
}
}
for i in d["available_projects"].keys():
print i, "=" , d["available_projects"][i]['available_models'][0]
输出:
model001 = model_20171004-090552
model002b = model_20171013-151458
model002 = model_20171013-143108
这篇关于解析嵌套的JSON响应Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!