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,
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With