如何检查json中的嵌套列表中是否存在键?

2024-10-01 17:34:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个JSON文件,其中每个对象都类似于以下示例:

[
  {
    "timestamp": 1569177699,
    "attachments": [

    ],
    "data": [
       {
         "post": "\u00f0\u009f\u0096\u00a4\u00f0\u009f\u0092\u0099"
       },
       {
         "update_timestamp": 1569177699
       }
    ],
    "title": "firstName LastName"
  }
]

我想检查是否有键post,嵌套在键data中。我写了这封信,但行不通:

 posts = json.loads(open(file).read())
 for post in posts:
     if 'data' in post:
        if 'post' in post['data']
            print post['data']['post']

Tags: 文件对象injson示例dataifpost
3条回答

试试这个答案这个有效!你知道吗

Elegant way to check if a nested key exists in a python dict

def keys_exists(element, *keys):
    '''
    Check if *keys (nested) exists in `element` (dict).
    '''
    if not isinstance(element, dict):
        raise AttributeError('keys_exists() expects dict as first argument.')
    if len(keys) == 0:
        raise AttributeError('keys_exists() expects at least two arguments, one given.')

    _element = element
    for key in keys:
        try:
            _element = _element[key]
        except KeyError:
            return False
    return True

尝试:

posts = json.loads(open(file).read())
for data in posts:
    for key, value in data.items():
        if key == 'data':
            for item in value:
                if 'post' in item:
                    print(key, item['post'])

这是我的解决办法。我从您的示例数据中看到post["data"]list,因此程序应该对其进行迭代:

posts = json.loads(open(file).read())
    for post in posts:
        if 'data' in post:
            #THIS IS THE NEW LINE to iterate list
            for d in post["data"]:
                if 'post' in d:
                    print d['post']

相关问题 更多 >

    热门问题