蟒蛇JSON只拿到第一级密钥(python JSON only get keys in first

2019-08-19 06:29发布

我有一个非常漫长而复杂的JSON对象,但我只是想在第一级的项目/钥匙!

例:

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

我想为1,3,8的结果!

我发现这个代码:

for key, value in data.iteritems():
    print key, value

但是,它打印的所有密钥(也12和25)

Answer 1:

只要做一个简单的.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
>>>

如果你需要一个排序列表:

keylist = dct.keys()
keylist.sort()


Answer 2:

for key in data.keys():
    print key


Answer 3:

检查Python对象是否是一个类型的实例的一个好方法是使用isinstance()这是Python的“内置”功能。 对于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


文章来源: python JSON only get keys in first level