使用Jayway Jsonpath过滤对象元素

huangapple go评论68阅读模式
英文:

Filter object elements with Jayway Jsonpath

问题

Here's the translation of the text you provided:

我有一组(某种程度上“表现良好”的)json路径,我必须返回一个仅包含列表中描述的元素的对象。例如,给定列表 ["$.a.a2", $.c] 和对象

{
    "a": {"a1": 1, "a2": 2},
    "b": foo,
    "c": []
}

期望的结果是

{
    "a": {"a2": 2},
    "c": []
}

我正在使用 Jayway Jsonpath,但我也可以使用其他库。我目前的解决方案如下:

  • 找到描述相同元素集的最小jsonpath列表(即如果"$.a"存在,则删除"$.a.a2");
  • 确定叶对象(在第一个示例中为a2c),并构建一个能够包含它们的映射,因为仍然不支持创建深层节点(不支持):在第一个示例中,在这一步之后,我正在创建一个映射{"a": {}}
  • 从初始对象中读取值,并使用提供的read/set方法将它们复制到映射中。

我对没有此功能感到非常惊讶。是否有更好的方法来过滤对象中的属性?Squiggly可能是一个合适的解决方案,但没有维护。

英文:

I have a list of (somehow "well-behaved") jsonpaths and I have to return an object which contains only the elements described in the list. For example, given the list ["$.a.a2", $.c] and the object

{
	"a": {"a1": 1, "a2": 2},
	"b": foo,
	"c": []
}

the desired result is

{
	"a": {"a2": 2},
	"c": []
}

I'm using Jayway Jsonpath, but I'm open to use other libraries. My current solution is the following:

  • find the minimal jsonpath list that describe the same set of elements (i.e. remove "$.a.a2" if "$.a" is present);
  • determine the leaf objects (in the first example a2 and c) and build a map that is capable to contain them, as creation of deep nodes is still not supported: in the first example, after this step I'm creating a map {"a": {}};
  • read the values from the initial object and copy them in the map with the provided methods read/set.

I'm quite surprised that such feature is not present. Is there a better way to filter properties in an object? Squiggly might be a suitable solution, but is not maintained.

答案1

得分: 1

你可以尝试另一个JSON库,名为_Josson_,使用带有函数 map() 的查询表达式。

链接:https://github.com/octomix/josson

Josson josson = Josson.fromJsonString(
    "{" +
    "    \"a\": {\"a1\": 1, \"a2\": 2}," +
    "    \"b\": \"foo\"," +
    "    \"c\": []" +
    "}");
JsonNode node = josson.getNode("map(a.map(a2), c)");
System.out.println(node.toPrettyString());

输出

{
  "a" : {
    "a2" : 2
  },
  "c" : [ ]
}

你可以将JSON输出的结构与这个重新格式化的查询表达式进行比较:

map(
  a.map(
    a2
  ),
  c
)
英文:

You may try another JSON library Josson using query expression with function map().

https://github.com/octomix/josson

Josson josson = Josson.fromJsonString(
    "{" +
    "    \"a\": {\"a1\": 1, \"a2\": 2}," +
    "    \"b\": \"foo\"," +
    "    \"c\": []" +
    "}");
JsonNode node = josson.getNode("map(a.map(a2), c)");
System.out.println(node.toPrettyString());

Output

{
  "a" : {
    "a2" : 2
  },
  "c" : [ ]
}

You can compare the structure of the JSON output with this re-formatted query expression:

map(
  a.map(
    a2
  ),
  c
)

huangapple
  • 本文由 发表于 2023年6月26日 16:05:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76554716.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定