5

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

Gray
  • 63
  • 1
  • 3
  • When you do `for element in jsonresponse[u'available_projects']:` you're iterating over the _keys_ of the dict (i.e. `element` is a string). You want to iterate over the dict's _values_ instead. – Aran-Fey Feb 05 '18 at 10:55

1 Answers1

6

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
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • Rakesh! You legend :) That's working perfectly - thank you so much. I've been tearing my hair out trying to get this to work :) – Gray Feb 05 '18 at 11:11