5

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)
4
  • 1
    "c" is a list. Try c[0].keys() Commented Dec 17, 2015 at 6:10
  • Do you need ['d','e','g'] or ['d','e','f'] keys? Commented Dec 17, 2015 at 6:14
  • name of the keys.. ['d','e','g'] not values of ['d','e','g'] Commented Dec 17, 2015 at 6:16
  • sorry, there are typo in comment. I have updated comment above. Commented Dec 17, 2015 at 6:19

2 Answers 2

7

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()

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks andriy.. It gave me ['e', 'd', 'f']. i want 'g' rather than 'f'. I think i need one more loop inside it.
yes but it wouldn't be best way ... need solution without recursion ?
yes please that would be very helpful. Thanks again @Andriy for your effort.
why this is fetching in the order ['e','d','g'] rather than ['d','e','g'].. its ok but just out of curiosity.
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.
0

Try this,

dct = {
    "a":1,
    "b":2,
    "c":[
         {
         "d":4,
         "e":5,
         "f":{
             "g":6
             }
         }
        ]
    }
k=dct["c"][0]
for key in k.keys(): 
    print key

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.