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

时间:2019-10-17 09:51:55

标签: python json

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>



<select class="jsSelect" onchange="$('.jsTextBox').val($(this).val())"> 
  <option value="1">1</option>
  <option value="2">2</option>
</select>
<input class="jsTextBox" onchange="if($(this).val()!=''){$('.jsSelect').append($('<option></option>').attr('value',$(this).val()).text($(this).val()));$('.jsSelect').val($(this).val());}" type="text" value="">

我要检查是否有键[ { "timestamp": 1569177699, "attachments": [ ], "data": [ { "post": "\u00f0\u009f\u0096\u00a4\u00f0\u009f\u0092\u0099" }, { "update_timestamp": 1569177699 } ], "title": "firstName LastName" } ] 嵌套在键post中。我写了这个,但是不起作用:

data

5 个答案:

答案 0 :(得分:2)

这是我的解决方案。我从您的样本数据中看到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']

答案 1 :(得分:0)

尝试:

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'])

答案 2 :(得分:0)

请尝试此答案,这有效!

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

答案 3 :(得分:0)

您可以通过使my answer适应问题How to find a particular json value by key?来实现此目的。

从某种意义上说,它是通用的,它并不关心JSON数据的结构细节,它只检查它在其中发现的每个字典。

import json

def find_values(id, json_file):
    results = []

    def _decode_dict(a_dict):
        try:
            results.append(a_dict[id])
        except KeyError:
            pass
        return a_dict

    json.load(json_file, object_hook=_decode_dict)  # Return value ignored.
    return len(results) > 0  # If there are any results, id was found.

with open('find_key_test.json', 'r') as json_file:
    print(find_values('post', json_file)) # -> True

答案 4 :(得分:0)

请尝试以下操作:

posts = json.loads(open(file).read())

for post in posts:
    if 'data' in post.keys():
        for data in post['data']:
            if 'post' in data.keys():
                print(data['post'])