python JSON only get keys in first level

PythonJsonPython 2.7IteratorKey

Python Problem Overview


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)

Python Solutions


Solution 1 - Python

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()
keylist.sort()

Solution 2 - Python

for key in data.keys():
    print key

Solution 3 - Python

As Karthik mentioned, dct.keys() will work but it will return all the keys in dict_keys type not in list type. So if you want all the keys in a list, then list(dct.keys()) will work.

Solution 4 - Python

A good way to check whether a python object is an instance of a type is to use isinstance() which is Python's 'built-in' function. For Python 3.6:

dct = {
       "1": "a", 
       "3": "b", 
       "8": {
            "12": "c", 
            "25": "d"
           }
      }

for key in dct.keys():
    if isinstance(dct[key], dict)== False:
       print(key, dct[key])
#shows:
# 1 a
# 3 b

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTeNNoXView Question on Stackoverflow
Solution 1 - PythonkarthikrView Answer on Stackoverflow
Solution 2 - PythonJoe FrambachView Answer on Stackoverflow
Solution 3 - PythonPraveen ManupatiView Answer on Stackoverflow
Solution 4 - PythonHafizur RahmanView Answer on Stackoverflow