使用jsonpath过滤嵌套的json数据,如示例所示

bqucvtff  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(774)

我正在使用jsonpath进行过滤。
json(dummy json just to explain)源字符串,它基本上是一个操作系统列表及其程序的详细信息等。在本例中,id=1403的操作系统是一个windows10操作系统,具有两个特性:架构和浏览器。浏览器特性的更多细节如json所示

  1. [
  2. {
  3. "id": 1403,
  4. "os": "window 10",
  5. "features": [
  6. {
  7. "id": 1356,
  8. "name": "architecture",
  9. "value": [
  10. {
  11. "id": 1308,
  12. "feature": [
  13. {
  14. "id": 1262,
  15. "key": "name",
  16. "value": "amd64"
  17. }
  18. ]
  19. }
  20. ],
  21. "category": "cat1"
  22. },
  23. {
  24. "id": 1357,
  25. "name": "browser",
  26. "value": [
  27. {
  28. "id": 1309,
  29. "feature": [
  30. {
  31. "id": 1263,
  32. "key": "name",
  33. "value": "Firefox"
  34. },
  35. {
  36. "id": 1265,
  37. "key": "version",
  38. "value": "187"
  39. }
  40. ]
  41. }
  42. ],
  43. "category": "cat2"
  44. }
  45. ]
  46. },
  47. {
  48. "id": 2804,
  49. "os": "window 7",
  50. "features": [
  51. {
  52. "id": 2764,
  53. "name": "architecture",
  54. "value": [
  55. {
  56. "id": 2719,
  57. "feature": [
  58. {
  59. "id": 2679,
  60. "key": "name",
  61. "value": "amd64"
  62. }
  63. ]
  64. }
  65. ],
  66. "category": "cat1"
  67. },
  68. {
  69. "id": 2765,
  70. "name": "browser",
  71. "value": [
  72. {
  73. "id": 2722,
  74. "feature": [
  75. {
  76. "id": 2685,
  77. "key": "name",
  78. "value": "Chrome"
  79. },
  80. {
  81. "id": 2684,
  82. "key": "version",
  83. "value": "87.0.4280.88"
  84. }
  85. ]
  86. }
  87. ],
  88. "category": "cat2"
  89. }
  90. ]
  91. }
  92. ]

我希望能够过滤json,以便

  1. features[*].name == 'browser' and features[*].value[*].feature[*].value == 'chrome'

可以帮助我实现上述查询的jsonpath字符串是什么?上面的查询使用了jsonpath string使用的类似语法,但不起作用。只是为了解释。
这里还有另一个例子,在“主演”字段中获得电影标题
并希望获得满足此条件的完整os json。在这种情况下,一个操作系统数组只包含一个操作系统,即id=2804

  1. [
  2. {
  3. "id": "2804",
  4. ...
  5. }
  6. ]

我在实现什么目标之前就被困住了。下面是我的代码,以获得所有的操作系统有“名称=浏览器”。我得到数组,但它只包含value[]项。我要它得到完整的json。它返回ID为-13572765的对象。

  1. List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString)
  2. .read("$[*].features[*].[?(@.name == 'browser')]");
4urapxun

4urapxun1#

要获得外部数组,需要使用如下过滤器 $[?(...)] 对于您当前的用例,我们需要使用嵌套数组过滤器。子级过滤器的jsonpath中存在一个未解决的问题(请参阅此处)。
幸运的是,有一个建议使用的解决方法 contains 在这里。
我们可以使用以下表达式进行筛选:

  1. List<Object> expensive = JsonPath.parse(jsonDataSourceString)
  2. .read("$[?(@.features[?(@.name == 'browser')].value[*].feature[*].value contains 'Chrome')]");

打印以下输出

  1. {id=2804, os=window 7, features=[{"id":2764,"name":"architecture","value":[{"id":2719,"feature":[{"id":2679,"key":"name","value":"amd64"}]}],"category":"cat1"},{"id":2765,"name":"browser","value":[{"id":2722,"feature":[{"id":2685,"key":"name","value":"Chrome"},{"id":2684,"key":"version","value":"87.0.4280.88"}]}],"category":"cat2"}]}

相关问题