python JSON只获取第一级的键

2022-01-10 00:00:00 python python-2.7 json key iterator

问题描述

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

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

例子:

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

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

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

我找到了这段代码:

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

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

But it prints all keys (also 12 and 25)


解决方案

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

相关文章