Python 如何索引到变量JSON输出

Python 如何索引到变量JSON输出,python,json,Python,Json,我使用的一个函数outputsJSON,在中显示文本中存在的任何实体。实体输出如下所示(示例): 我对值对象特别感兴趣。我知道如何提取任意值['entities'][I]['value']。我想知道的是如何检查某个键值对是否存在,例如“value”:“pool”。我不知道他们的位置会是什么,因为取决于文本输入,如果文本中没有实体,那么“实体”甚至不会出现在JSON中,您可以这样理解列表 pools = [x for x in jsondata['entities'] if x.get('valu

我使用的一个函数outputs
JSON
,在中显示文本中存在的任何实体。实体输出如下所示(示例):


我对
对象特别感兴趣。我知道如何提取任意值
['entities'][I]['value']
。我想知道的是如何检查某个键值对是否存在,例如
“value”:“pool”
。我不知道他们的位置会是什么,因为取决于文本输入,如果文本中没有实体,那么“实体”甚至不会出现在
JSON

中,您可以这样理解列表

pools = [x for x in jsondata['entities'] if x.get('value') == 'pool']
if pools:
    print("pools found")

我使用.get('value')而不是['value']的原因是为了防止引发keynotfound错误。

您可以使用json模块将json字符串转换为python数据类型。从这里,您可以迭代字典并检查键的“值”

可以使用
filter()
检查:

checkThis = ['foo', 'bar']
isThere = list(filter(lambda x: 'value' in x and x['value'] in checkThis, json['entities']))
if isThere:
    print('Yes !')
else:
    print('No !')

JSON
的结构始终与您作为示例发布的结构相同,否?一般结构是的,但是实体的数量及其顺序是可变的。您可以在对象列表上循环并检查任何过滤数据的内容
import json

json_str = """
[
        {
            "end": 3,
            "entity": "pet",
            "extractor": "ner_crf",
            "processors": [
                "ner_synonyms"
            ],
            "start": 0,
            "value": "Pet"
        },
        {
            "end": 8,
            "entity": "aquatic_facility",
            "extractor": "ner_crf",
            "start": 4,
            "value": "pool"
        },
        {
            "end": 14,
            "entity": "toiletries",
            "extractor": "ner_crf",
            "start": 9,
            "value": "razor"
        }
    ]
"""

data = json.loads(json_str)

values = []

for record in data:
    if "value" in record:
        values.append(record["value"])

print(values)
checkThis = ['foo', 'bar']
isThere = list(filter(lambda x: 'value' in x and x['value'] in checkThis, json['entities']))
if isThere:
    print('Yes !')
else:
    print('No !')