You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JSON Path检查字符串列表中是否存在指定值

检查JSON列表中是否存在指定值的方法

给定如下JSON数据,我们需要判断指定值(例如name1)是否存在于listToCheck数组中:

{
    "firstName": "John",
    "lastName": "doe",
    "age": 26,
    "listToCheck" : [
        "name1", "name2"
    ],
    "address": {
        "streetAddress": "naist street",
        "city": "Nara",
        "postalCode": "630-0192"
    },
    "phoneNumbers": [
        {
            "type": "iPhone",
            "number": "0123-4567-8888"
        },
        {
            "type": "home",
            "number": "0123-4567-8910"
        }
    ]
}

以下是几种实用的实现方式:

1. 使用JSONPath查询

如果用JSONPath工具查询,可通过以下表达式匹配目标值:

$..listToCheck[?(@ == 'name1')]

执行该查询后,若返回非空数组,则说明name1存在于listToCheck列表中。

2. Python代码实现

直接解析JSON并判断值是否在目标列表中:

import json

# 加载JSON数据
json_data = '''
{
    "firstName": "John",
    "lastName": "doe",
    "age": 26,
    "listToCheck" : [
        "name1", "name2"
    ],
    "address": {
        "streetAddress": "naist street",
        "city": "Nara",
        "postalCode": "630-0192"
    },
    "phoneNumbers": [
        {
            "type": "iPhone",
            "number": "0123-4567-8888"
        },
        {
            "type": "home",
            "number": "0123-4567-8910"
        }
    ]
}
'''

data = json.loads(json_data)
target_value = "name1"

# 判断存在性
if target_value in data["listToCheck"]:
    print(f"{target_value} 存在于列表中")
else:
    print(f"{target_value} 不存在于列表中")

3. JavaScript代码实现

利用数组的includes方法快速判断:

const jsonData = {
    "firstName": "John",
    "lastName": "doe",
    "age": 26,
    "listToCheck" : [
        "name1", "name2"
    ],
    "address": {
        "streetAddress": "naist street",
        "city": "Nara",
        "postalCode": "630-0192"
    },
    "phoneNumbers": [
        {
            "type": "iPhone",
            "number": "0123-4567-8888"
        },
        {
            "type": "home",
            "number": "0123-4567-8910"
        }
    ]
};

const targetValue = "name1";
const exists = jsonData.listToCheck.includes(targetValue);

console.log(exists ? `${targetValue} 存在于列表中` : `${targetValue} 不存在于列表中`);

内容的提问来源于stack exchange,提问作者user_pvr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 08:12:20