You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Java如何借助JsonPath向现有JSON的数组开头插入新节点?

解决方案

你当前使用的add()方法默认是向目标数组的尾部追加元素,所以插入的myValue会出现在原有对象之后。要插入到数组的头部(索引为0的位置),可以参考以下两种实现方式:


方式一:使用insert方法(适用于Jayway JsonPath 2.4.0及以上版本)

直接通过insert方法指定插入位置的索引即可,索引0对应数组的第一个位置:

String originalJson = "{\"checkouts\":[{\"line_items\":[{\"id\":\"343f1f49d0ba7752b5ba84e0184384f4\"}]}]}";
String modifiedJson = JsonPath.parse(originalJson)
        .insert("$.checkouts[0].line_items", 0, "myValue")
        .jsonString();

方式二:手动修改数组后替换(兼容所有版本)

如果你的JsonPath版本较低没有提供insert方法,可以先读取目标数组,手动在头部插入元素后再替换原数组:

String originalJson = "{\"checkouts\":[{\"line_items\":[{\"id\":\"343f1f49d0ba7752b5ba84e0184384f4\"}]}]}";
DocumentContext context = JsonPath.parse(originalJson);
List<Object> lineItems = context.read("$.checkouts[0].line_items");
// 往列表头部插入元素
lineItems.add(0, "myValue");
// 替换原数组内容
context.set("$.checkouts[0].line_items", lineItems);
String modifiedJson = context.jsonString();

两种方式最终输出的结果都和你预期的一致:

{"checkouts":[{"line_items":["myValue",{"id":"343f1f49d0ba7752b5ba84e0184384f4"}]}]}

内容的提问来源于stack exchange,提问作者Nikunj Aggarwal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 02:39:02