python JSON只获取第一级的键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15789059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:00:37  来源:igfitidea点击:

python JSON only get keys in first level

pythonjsonpython-2.7iteratorkey

提问by TeNNoX

I have a very long and complicated json object but I only want to get the items/keys in the first level!

我有一个非常长且复杂的 json 对象,但我只想获取第一级中的项目/键!

Example:

例子:

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

I want to get 1,3,8as result!

我想得到1,3,8结果!

I found this code:

我找到了这个代码:

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

But it prints all keys (also 12 and 25)

但它打印所有键(还有12 和 25

采纳答案by karthikr

Just do a simple .keys()

做一个简单的 .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()

回答by Frambot

for key in data.keys():
    print key

回答by Hafizur Rahman

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:

检查 Python 对象是否是类型实例的一个好方法是使用isinstance()which 是 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

回答by Praveen Manupati

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

正如 Karthik 所提到的,dct.keys()会起作用,但它会返回所有dict_keys类型的键,而不是list类型。所以如果你想要一个列表中的所有键,那么list(dct.keys())就可以了。