Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for Json-path/(any API) to update any value in given json string in Java

Tags:

java

json

Inshort : I am trying to find some api that could just change the value by taking first parameter as jsonString , second parameter as JSONPath and third will be new value of that parameter. But, all I found is this.. https://code.google.com/p/json-path/

This api allows me to find any value in JSON String. But, I am not finding easy way to update the value of any key. For example, Here is a book.json.

{
"store":{
    "book":[
        {
            "category":"reference",
            "author":"Nigel Rees",
            "title":"Sayings of the Century",
            "price":8.95
        },
        {
            "category":"fiction",
            "author":"Evelyn Waugh",
            "title":"Sword of Honour",
            "price":12.99,
            "isbn":"0-553-21311-3"
        }
    ],
    "bicycle":{
        "color":"red",
        "price":19.95
    }
   }
 }

I can access color of bicycle by doing this.

String bicycleColor = JsonPath.read(json, "$.store.bicycle.color");

But I am looking for a method in JsonPath or other api some thing like this

    JsonPath.changeNodeValue(json, "$.store.bicycle.color", "green");
    String bicycleColor = JsonPath.read(json, "$.store.bicycle.color");
    System.out.println(bicycleColor);  // This should print "green" now. 

I am excluding these options,

  • Create a new JSON String.
  • Create a JSON Object to deal with changing value and convert it back to jsonstring

Reason: I have about 500 different requests for different types of service which return different json structure. So, I do not want to manually create new JSON string always. Because, IDs are dynamic in json structure.

Any idea or direction is much appreciated.

Updating this question with following answer.

  1. Copy MutableJson.java.
  2. copy this little snippet and modify as per you need.

    private static void updateJsonValue() {
    
    JSONParser parser = new JSONParser();
    JSONObject jsonObject = new JSONObject();
    
    FileReader reader = null;
    try {
        File jsonFile = new File("path to book.json");
        reader = new FileReader(jsonFile);
        jsonObject = (JSONObject) parser.parse(reader);
    
    } catch (Exception ex) {
        System.out.println(ex.getLocalizedMessage());
    }
    
    Map<String, Object> userData = null;
    try {
        userData = new ObjectMapper().readValue(jsonObject.toJSONString(), Map.class);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
    MutableJson json = new MutableJson(userData);
    
    System.out.println("Before:\t" + json.map());
    
    json.update("$.store.book[0].author", "jigish");
    json.update("$.store.book[1].category", "action");
    
    System.out.println("After:\t" + json.map().toString());
    
    }
    

Use these libraries.

  • import org.json.simple.JSONObject;
  • import org.json.simple.parser.JSONParser;
  • import org.codehaus.jackson.map.ObjectMapper;
like image 541
JLP Avatar asked Aug 20 '14 14:08

JLP


People also ask

How do I check if JSON path exists in JSON?

use the Deserialize activity (Deserialize Json) and you can check any element in the JSON or do any operations on it, as needed.

How do I reference a path in JSON?

In a JSON schema, a $ref keyword is a JSON Pointer to a schema, or a type or property in a schema. A JSON pointer takes the form of A # B in which: A is the relative path from the current schema to a target schema. If A is empty, the reference is to a type or property in the same schema, an in-schema reference.

How do you evaluate a JSON path?

You can open up a window to evaluate JSONPath expressions by going to Edit -> Find -> "Evaluate JSONPath Expression...". If a JSON file is open, it will use this file to evaluate the expression. If you have JSONPath expressions as Strings in code, use "inject language" and say this is a JSONPath expression.

What is JSON path expression?

JsonPath expressions always refer to a JSON structure in the same way as XPath expression are used in combination with an XML document. The "root member object" in JsonPath is always referred to as $ regardless if it is an object or array. JsonPath expressions can use the dot–notation. $.store.book[0].title.


1 Answers

The thing is that the functionality you want is already an undocumented feature of JsonPath. Example using your json structure:

String json = "{ \"store\":{ \"book\":[ { \"category\":\"reference\", \"author\":\"Nigel Rees\", \"title\":\"Sayings of the Century\", \"price\":8.95 }, { \"category\":\"fiction\", \"author\":\"Evelyn Waugh\", \"title\":\"Sword of Honour\", \"price\":12.99, \"isbn\":\"0-553-21311-3\" } ], \"bicycle\":{ \"color\":\"red\", \"price\":19.95 } } }";
DocumentContext doc = JsonPath.parse(json).
    set("$.store.bicycle.color", "green").
    set("$.store.book[0].price", 9.5);
String newJson = new Gson().toJson(doc.read("$"));
like image 122
Homyk Avatar answered Sep 28 '22 16:09

Homyk