4

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 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

import com.jayway.jsonpath.JsonPath; Add this import if not added.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.