Java - use jsonPath to update Json based on current value

8.7k views Asked by At

I managed to update a json object using a jsonPath with this code

JSONObject json = new JSONObject("{\"data\":[{\"city\":\"New York\",\"name\":\"John\",\"age\":31},{\"city\":\"Paris\",\"name\":\"Jack\",\"age\":12}]}");
DocumentContext doc = JsonPath.parse(json.toString())
                .set("$..name","newName");
System.out.println("doc.jsonString() = " + doc.jsonString());

outputs:

doc.jsonString() = {"data":[{"city":"New York","name":"newName","age":31},{"city":"Paris","name":"newName","age":12}]}

Now I would like to update the value depending on the old value (by applying a function on the old value)
Something like

DocumentContext doc = JsonPath.parse(json.toString())
                .set("$..name",upper(oldValue))
                .set("$..age", oldValue+10);

That would result in the following json

 doc.jsonString() = doc.jsonString() = {"data":[{"city":"New York","name":"JOHN","age":41},{"city":"Paris","name":"JACK","age":22}]}

Does someone know how I can manage to reference the old value like that ?
Regards,

2

There are 2 answers

0
Vinícius Biavatti On BEST ANSWER

You can use the map function of the DocumentContext class like the example below:

DocumentContext json = JsonPath.using(configuration).parse(jsonStr);
DocumentContext result = json.map("$..name", (currentValue, configuration) -> {
    return currentValue.toString().toUpperCase();
});
System.out.println(result.jsonString());

That example change the value to uppercase.

Try to check about it in the Jsonpath DocumentContext class documentation.

1
Yogesh Kolhe On

You can use parse and set functions of JsonPath.

example:

public static String replaceOldValueVithNewValueforGivenPath(String jsonBody, String path, String newValue)
{
   // validateJsonInput(jsonBody);
    try {
        return JsonPath.parse(jsonBody).set(path,newValue).jsonString();
    } catch (PathNotFoundException var3) {
        throw new RuntimeException("No results for path: " + path);
    }
}