问题描述
{ "items": [
{ "x": 1 },{ "x": 2 },{ "x": 3 },{ "x": 4 }]
}
$.items[:].x
给出...
[
1,2,3,4
]
例如,我可以让它返回...
[
{ 1 },{ 2 },{ 3 },{ 4 }
]
解决方法
正如评论中所讨论的,这不能单独使用JSONPath来完成,因为路径查询仅返回有效的JSON并且目标格式无效。通常,JSONPath在这里不是合适的工具,使用Jolt之类的库进行JSON转换会更合适;但是同样,类似于XSLT转换,我们只能创建有效的输出。因此,正如您已经发现的那样,您将需要使用字符串函数根据需要混合代码。例如,正则表达式替换可以做到:
const regex = /(\d+),?/gm;
const str = `[
1,2,3,4
]`;
const subst = `{ $1 },`;
// The substituted value will be contained in the result variable
const result = str.replace(regex,subst);
console.log('Substitution result: ',result);