Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python JSON only get keys in first level

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)

like image 583
TeNNoX Avatar asked Apr 03 '13 13:04

TeNNoX


People also ask

Can JSON have only keys?

The JSON format is deliberately based on a subset of JavaScript object literal syntax and array literal syntax, and JavaScript objects can only have strings as keys - thus JSON keys are strings too.

Does JSON preserve key order?

Yes, the order of elements in JSON arrays is preserved.


1 Answers

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() 
like image 55
karthikr Avatar answered Sep 22 '22 21:09

karthikr