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

如何在C++中通过JSON Schema路径检索指定JSON键值?

从JSON中提取JSON Schema指定路径的值

我之前做过类似的JSON数据提取需求,刚好能给你一些实用的实现思路和代码示例!核心就是两步:先确定JSON Schema中合法的目标路径,再根据路径从JSON数据中精准取值。

一、基础实现:直接按给定路径提取值

如果已经明确了所有需要提取的路径(就是你列出的那些),可以先写一个路径解析函数,用来从JSON对象中根据路径获取对应值:

路径解析函数(Python示例)

def get_value_from_path(json_data, path):
    """根据斜杠分隔的路径从JSON数据中取值"""
    # 移除路径开头的斜杠,拆分成路径段
    segments = path.lstrip('/').split('/')
    current_data = json_data
    
    try:
        for seg in segments:
            # 处理数组索引(将字符串转为整数)
            if seg.isdigit():
                seg = int(seg)
            current_data = current_data[seg]
        return current_data
    except (KeyError, IndexError, TypeError):
        # 路径不存在时返回None(可根据需求自定义)
        return None

批量提取目标路径的值

接下来把你需要的路径整理成列表,批量提取并过滤掉不存在的路径:

# 你的目标路径列表
target_paths = [
    "/array/0",
    "/boolean",
    "/null",
    "/object/a",
    "/object/c",
    "/object/e",
    "/number",
    "/deep_nested_array/0/object_array1/0/key4",
    "/deep_nested_array/0/object_array1/1/key5",
    "/deep_nested_array/0/object_array1/2/key6",
    "/object_array/0/key1",
    "/object_array/1/key2"
    # 补充剩余的路径...
]

def extract_target_values(json_data, target_paths):
    """批量提取目标路径的值,仅保留存在的路径"""
    extracted_result = {}
    for path in target_paths:
        value = get_value_from_path(json_data, path)
        if value is not None:
            extracted_result[path] = value
    return extracted_result

# 示例使用
sample_json = {
    "array": ["foo", "bar"],
    "boolean": True,
    "null": None,
    "object": {"a": 1, "b": 2, "c": 3, "d":4, "e":5},
    "number": 123.45,
    "deep_nested_array": [
        {
            "object_array1": [
                {"key4": "val4"},
                {"key5": "val5"},
                {"key6": "val6"}
            ]
        }
    ],
    "object_array": [
        {"key1": "val1"},
        {"key2": "val2"},
        {"key3": "val3"}
    ]
}

# 执行提取
result = extract_target_values(sample_json, target_paths)
print(result)

运行后会得到一个字典,键是存在的路径,值是对应的JSON内容,完全符合你的需求。

二、进阶实现:先验证路径是否在JSON Schema中存在

如果需要严格确保提取的路径都是JSON Schema中定义过的,可以先遍历Schema生成所有合法路径,再和你的目标路径做交集,避免提取Schema以外的键:

从JSON Schema生成合法路径

def generate_valid_schema_paths(schema, parent_path=""):
    """递归遍历JSON Schema,生成所有合法的访问路径"""
    valid_paths = []
    
    # 处理对象类型的Schema
    if schema.get("type") == "object" and "properties" in schema:
        for prop_name, prop_schema in schema["properties"].items():
            current_path = f"{parent_path}/{prop_name}"
            valid_paths.append(current_path)
            # 递归处理嵌套对象
            valid_paths.extend(generate_valid_schema_paths(prop_schema, current_path))
    
    # 处理数组类型的Schema
    elif schema.get("type") == "array" and "items" in schema:
        items_schema = schema["items"]
        if isinstance(items_schema, list):
            # 数组每个元素有独立Schema,按索引生成路径
            for idx, item_schema in enumerate(items_schema):
                current_path = f"{parent_path}/{idx}"
                valid_paths.append(current_path)
                valid_paths.extend(generate_valid_schema_paths(item_schema, current_path))
        else:
            # 数组所有元素Schema相同,用示例索引(如/0)生成路径
            current_path = f"{parent_path}/0"
            valid_paths.append(current_path)
            valid_paths.extend(generate_valid_schema_paths(items_schema, current_path))
    
    return valid_paths

过滤并提取合法路径的值

# 示例JSON Schema(根据你的实际Schema替换)
sample_schema = {
    "type": "object",
    "properties": {
        "array": {"type": "array", "items": {"type": "string"}},
        "boolean": {"type": "boolean"},
        "null": {"type": "null"},
        "object": {
            "type": "object",
            "properties": {"a": {"type": "integer"}, "c": {"type": "integer"}, "e": {"type": "integer"}}
        },
        "number": {"type": "number"},
        "deep_nested_array": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "object_array1": {
                        "type": "array",
                        "items": [
                            {"type": "object", "properties": {"key4": {"type": "string"}}},
                            {"type": "object", "properties": {"key5": {"type": "string"}}},
                            {"type": "object", "properties": {"key6": {"type": "string"}}}
                        ]
                    }
                }
            }
        },
        "object_array": {
            "type": "array",
            "items": [
                {"type": "object", "properties": {"key1": {"type": "string"}}},
                {"type": "object", "properties": {"key2": {"type": "string"}}}
            ]
        }
    }
}

# 生成Schema中的所有合法路径
valid_paths = generate_valid_schema_paths(sample_schema)
# 过滤出目标路径中存在于Schema的部分
filtered_target_paths = [path for path in target_paths if path in valid_paths]
# 提取值
final_result = extract_target_values(sample_json, filtered_target_paths)
print(final_result)

这样就能100%保证提取的都是JSON Schema中定义过的键对应的值,完全符合你的要求。

内容的提问来源于stack exchange,提问作者A.v

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:50:43