Nikunj Aggarwal
Nikunj Aggarwal

Reputation: 825

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"}]}]}

Upvotes: 0

Views: 699

Answers (1)

tgdavies
tgdavies

Reputation: 11431

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();

Upvotes: 1

Related Questions