python JSON only get keys in first level

iterator, json, key, python, python-2.7

Solution

Just do a simple `.keys()`

>>> dct = {
...     "1": "a", 
...     "3": "b", 
...     "8": {
...         "12": "c", 
...         "25": "d"
...     }
... }
>>> 
>>> dct.keys()
['1', '8', '3']
>>> for key in dct.keys(): print key
...
1
8
3
>>>

If you need a sorted list:

keylist = dct.keys() # this is of type `dict_key`, NOT a `list`
keylist.sort()

And if you want them as simple list, do this:

list(dct_instance.keys())

Problem

I have a very long and complicated json object but I only want to get the items/keys in the first level! Example: ``` { "1": "a", "3": "b", "8": { "12": "c", "25": "d" } } ``` I want to get 1,3,8 as result! I found this code: ``` for key, value in data.iteritems(): print key, value ``` But it prints all keys (also 12 and 25)

Original source

Related problems