将字符串文字添加到 JSONPath 输出中

Add string literal into JSONPath output

我可以将字符串文字添加到 JSONPath 选择器吗?

{ "items": [
    { "x": 1 },
    { "x": 2 },
    { "x": 3 },
    { "x": 4 }]
}

$.items[:].x 给出...

[
  1,
  2,
  3,
  4
]

例如,我可以做到吗return...

[
  { 1 },
  { 2 },
  { 3 },
  { 4 }
]

我想生成一些向字典添加项目的代码。

正如评论中所讨论的,这不能使用 JSONPath(单独)来完成,因为路径查询 returns 仅有效 JSON 而目标格式无效。一般来说,JSONPath 在这里不是合适的工具,使用像 Jolt 这样的库的 JSON 转换会更合适;但同样,与 XSLT 转换类似,我们只能创建有效输出。因此,正如您已经发现的那样,您需要使用字符串函数来根据需要混合代码。例如,正则表达式替换可以做:

const regex = /(\d+),?/gm;
const str = `[
  1,
  2,
  3,
  4
]`;
const subst = `{  },`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);