能否用JSONPath同时提取多个指定键值?技术咨询
问题:如何用JSONPath同时提取符合条件的id和label键值对?
给定简化后的JSON(已修正语法问题):
{ "data": { "134001": { "id": 134001, "label": "Deutsche Telekom", "is_active": true }, "134002": { "id": 134002, "label": "T-Mobile", "is_active": false }, "134004": { "id": 134004, "label": "1&1", "is_active": true }, "134005": { ... } } }
目前已能通过以下JSONPath语句分别提取目标数据:
- 获取所有
is_active为true的label值:$.data..[?(@.is_active==true)].label - 获取对应
id值:$.data..[?(@.is_active==true)].id
但需要同时提取符合条件条目的id和label键值对,原JSON包含大量其他字段,请问仅通过JSONPath能否实现?若不能,需使用哪些工具?
回答
1. 部分JSONPath实现支持此需求
JSONPath没有统一官方标准,不同实现的功能差异较大:
Jayway JSONPath(Java生态常用)和JSONPath Plus(JavaScript)支持对象投影,可直接构造包含指定键的结果:
$.data.*[?(@.is_active==true)].{id: @.id, label: @.label}或者用数组指定要保留的键:
$.data.*[?(@.is_active==true)]['id','label']执行后会返回类似如下结构的结果:
[ {"id":134001,"label":"Deutsche Telekom"}, {"id":134004,"label":"1&1"} ]若使用的是原始Stefan Goessner的JSONPath实现(最基础版本),则不支持同时提取多个指定键,只能返回整个符合条件的对象,再手动过滤掉不需要的字段。
2. 替代工具方案
如果你的JSONPath实现不支持投影,推荐以下工具:
- jq(命令行工具):轻量高效,适合批量处理JSON数据,命令示例:
jq '.data | to_entries[] | select(.value.is_active == true) | {id: .value.id, label: .value.label}' your_file.json - Python + jsonpath-ng:结合JSONPath查询和Python字典处理,示例代码:
from jsonpath_ng import parse import json with open('your_file.json') as f: data = json.load(f) jsonpath_expr = parse("$.data.*[?(@.is_active==true)]") results = [{"id": match.value["id"], "label": match.value["label"]} for match in jsonpath_expr.find(data)] print(results) - JavaScript + lodash:前端或Node.js环境下,用JSONPath筛选对象后,用
_.pick提取指定键:const jsonpath = require('jsonpath'); const _ = require('lodash'); const data = require('./your_file.json'); const matches = jsonpath.query(data, "$.data.*[?(@.is_active==true)]"); const result = matches.map(item => _.pick(item, ['id', 'label'])); console.log(result);
内容的提问来源于stack exchange,提问作者metawops
相关产品推荐
相关产品推荐

