问题
I've been stuck on this all weekend, can anybody help me out please?
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...
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.
Sample JSON response:
{
"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"
}
}
My Code:
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
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!!
回答1:
You can use the keys method in the dictionary object to fetch the keys and then iterate over to get the required value.
Example:
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]
Output:
model001 = model_20171004-090552
model002b = model_20171013-151458
model002 = model_20171013-143108
来源:https://stackoverflow.com/questions/48620892/parsing-nested-json-response-python