Search code examples
javajsonjsonpath

Using Java, how to add some node to an existing json at the start of array?


The below code inserts the "myvalue" field to the existing JSON but after the "id" key-value pair, I want to insert a value in this JSON but before the "id" field.

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

The current output of the above code is :

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

But I want an output like this :

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

Solution

  • You can do this:

            String originalJson="{\"checkouts\":[{\"line_items\":[{\"id\":\"343f1f49d0ba7752b5ba84e0184384f4\"}]}]}";
            DocumentContext json = JsonPath.parse(originalJson);
            JSONArray array = json.read("$.checkouts[0].line_items");
            array.add(0, "myValue");
            String modifiedJson= json
                    .set("$.checkouts[0].line_items",array)
                    .jsonString();