Get keys from json in python

16,266

Function which return only keys which aren't containing dictionary as their value.

jsonData = {
    "a": 1,
    "b": 2,
    "c": [{
        "d": 4,
        "e": 5,
        "f": {
            "g": 6
        }
    }]
}


def get_simple_keys(data):
    result = []
    for key in data.keys():
        if type(data[key]) != dict:
            result.append(key)
        else:
            result += get_simple_keys(data[key])
    return result

print get_simple_keys(jsonData['c'][0])

To avoid using recursion change line result += get_simple_keys(data[key])to result += data[key].keys()

Share:
16,266
Sagar
Author by

Sagar

Updated on June 14, 2022

Comments

  • Sagar
    Sagar about 2 years

    I have an API whose response is json like this:

    {
    "a":1,
    "b":2,
    "c":[
         {
         "d":4,
         "e":5,
         "f":{
             "g":6
             }
         }
        ]
    }
    

    How can I write a python program which will give me the keys ['d','e','g']. What I tried is:

    jsonData = request.json() #request is having all the response which i got from api
    c = jsonData['c']
    for i in c.keys():
        key = key + str(i)
    print(key)
    
  • Sagar
    Sagar over 8 years
    Thanks andriy.. It gave me ['e', 'd', 'f']. i want 'g' rather than 'f'. I think i need one more loop inside it.
  • Andriy Ivaneyko
    Andriy Ivaneyko over 8 years
    yes but it wouldn't be best way ... need solution without recursion ?
  • Sagar
    Sagar over 8 years
    yes please that would be very helpful. Thanks again @Andriy for your effort.
  • Sagar
    Sagar over 8 years
    why this is fetching in the order ['e','d','g'] rather than ['d','e','g'].. its ok but just out of curiosity.
  • Andriy Ivaneyko
    Andriy Ivaneyko over 8 years
    Python dictionaries are actually are hash tables. Among other things, that means the order of the keys isn't guaranteed or even specified. If you need to get them sorted use sorted(data.keys()) before iterating them.