简体   繁体   English

如何仅使用jsonpath将数组转换为子集?

[英]How to transform an array into a subset using only jsonpath?

I'd like to use jsonpath to transform an array with 3 elements to just 2 elements. 我想使用jsonpath将具有3个元素的数组转换为仅2个元素。

Given this object: 给定此对象:

var _base = {
    myArray: [{ item: 1, value: "first" }, { item: 2, value: "second" }, { item: 3, value: "third" }]
}

I'd like to use jsonpath-object transform to transform the object into: 我想使用jsonpath-object transform transform将对象转换为:

var _newBase = {
    myArray: [{ newItem: 2, newValue: "second" }, { newItem: 3, newValue: "third" }]
}

I understand I could do this with a simple slice call and some object manipulation, but I have complex, variable objects that I'm transforming at runtime, so jsonpath is the requirement. 我知道我可以通过一个简单的slice调用和一些对象操作来做到这一点,但是我有一些复杂的,可变的对象,我会在运行时进行转换,因此需要jsonpath

I'm able to use the below: 我可以使用以下内容:

var transform = require('jsonpath-object-transform');
var template = { ["$.myArray", { "newItem": "$..item", "newValue": "$..value" }] }
transform(_base, _template) //emits the below

Which emits: 发出:

[{ newItem: 1, newValue: "one" }, { newItem: 2, newValue: "second" }, { newItem: 3, newValue: "third" }]

But what I really need is the above object without its first index (so just the last two objects in the array). 但是我真正需要的是上面的对象没有它的第一个索引(所以只有数组中的最后两个对象)。

You can use the @path syntax to ignore the first item: 您可以使用@path语法忽略第一项:

var _template = {
  foo: ['$.myArray[?(@path !== "$[\'myArray\'][0]")]']
};

Returns: 返回:

{ foo: [ { item: 2, value: 'second' }, { item: 3, value: 'third' } ] }

However, it seems that jsonpath-object transform currently doesn't support mixing both @path and accessing subfields like in {["$.data", {"key": "$.value"}]} . 但是,似乎jsonpath-object转换当前不支持混合@path和访问{["$.data", {"key": "$.value"}]}子字段。 So this leaves you with the following options: 因此,您可以使用以下选项:

  • You can acheive what you need by using two transform operations: the first to prune out the first item, and the second to rename subfields. 您可以使用两个转换操作来实现所需的功能:第一个修剪掉第一个项目,第二个修剪重命名子字段。
  • slice -ing your objects beforehand, as you suggested. 根据您的建议,先对对象进行slice
  • And finally, patching the library (and submitting a pull request while you're at it!). 最后,修补库(并在使用时提交拉取请求!)。 It's probably a quick fix anyway, shouldn't be too time-consuming. 无论如何,这可能是一个快速修复,应该不会太耗时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM