【问题标题】:How to Add New Array Index in JSON using JsonPath?如何使用 JsonPath 在 JSON 中添加新的数组索引?
【发布时间】:2020-06-22 13:26:02
【问题描述】:

我正在尝试向路径添加一个索引值:

$.data.library.category[2].book 使用 jayway jsonpath 跟随 Json,

 "data":{
    "library":{
    "class":"CRED",
    "category":[{
                "book":"java 2.0"
            },
            {
                "book":"java 3.0"
            }]
    }

但我没有在结果 json 中得到更新的响应。

我的java代码:

Configuration conf = Configuration.defaultConfiguration().addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL).addOptions(Option.SUPPRESS_EXCEPTIONS);  
DocumentContext documentContext = JsonPath.using(conf).parse(sampleJson);
documentContext.set(JsonPath.compile("$.data.library.category[2].book"), "java 3.0");

我也检查了documentContext.add。什么都解决不了。由于数组有 0 和 1 索引,我可以通过 JsonPath 更新那里的值。但它没有第二个索引,所以没有更新。但我需要根据 jsonpath 在给定 json 的最后一个插入新索引。

【问题讨论】:

  • 我认为 JsonParser 使用 LIST 作为 JSON 数组的后端。所以你必须使用 .get(index)。

标签: java json jackson jsonpath json-path-expression


【解决方案1】:

路径$.data.library.category[2].book 表示要更新数组中的3-rd 元素。但是还没有3-rd 元素。您需要先创建它。您可以使用$.data.library.category 路径向数组添加新元素。通过提供Map 对象,您可以定义所有必需的键和值。见下例:

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;

import java.io.File;
import java.util.Collections;

public class JsonPathApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        Configuration conf = Configuration.defaultConfiguration()
                .addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL)
                .addOptions(Option.SUPPRESS_EXCEPTIONS);
        DocumentContext document = JsonPath.using(conf).parse(jsonFile);

        JsonPath pathToArray = JsonPath.compile("$.data.library.category");

        document.add(pathToArray, Collections.singletonMap("book", "java 3.1"));
        document.add(pathToArray, Collections.singletonMap("book", "java 3.2"));

        System.out.println(document.jsonString());
    }
}

上面的代码打印在JSON下面:

{
   "data":{
      "library":{
         "class":"CRED",
         "category":[
            {
               "book":"java 2.0"
            },
            {
               "book":"java 3.0"
            },
            {
               "book":"java 3.1"
            },
            {
               "book":"java 3.2"
            }
         ]
      }
   }
}

【讨论】:

  • 嗨,在这种情况下,它不会适用于所有情况,对吧?例如:您是硬编码路径:$.data.library.category 但是,同样的情况,如果库也是一个数组,我需要在以下路径中插入:$.data.library[2].category[2] 我们如何实现这个?
  • @MageshMagi,您需要更新一个问题并描述您想要处理的所有极端情况。
猜你喜欢
  • 2019-01-28
  • 2016-03-30
  • 2013-03-24
  • 1970-01-01
  • 2016-05-16
  • 1970-01-01
  • 2016-04-07
  • 1970-01-01
  • 2014-10-20
相关资源
最近更新 更多