Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set specific JSONPATH element value

Tags:

java

jsonpath

I was trying to set the author value from the following JSON text but my code is removing the all other child's of the json text.

   {
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "XXXXXXXXXXXXXXXXX",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": XXXXXXXXXXXXXXXXXXXXX
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

I tried to update the author in first book to some other value as below.

Object updatedJson = JsonPath.using(configuration).parse(jsonInput).json();
String jayPath = "$..book[0].author";
String tagValue = "ReplacedText";
                String jsonToParse = updatedJson.toString();
                updatedJson = JsonPath.parse(jsonToParse).set(jayPath, tagValue).json();

After set step my json has only content of book[1] like below. Please advise how can I get the entire json input which I gave with the replaced values as output.

{store={book=[{"category"=reference, author=XXXXXXXXXXXXXXXXX, title=Sayings of the Century, price=8.95}

Regards, Sathish.

like image 869
user741699 Avatar asked Jan 23 '17 14:01

user741699


1 Answers

Works fine without converting DocumentContext to json

public static void main(String[] args) {
    DocumentContext json = JsonPath.using(configuration).parse(jsonInput);
    String jayPath = "$..book[0].author";
    String tagValue = "ReplacedText";
    System.out.println(json.set(jayPath, tagValue).jsonString());
}
like image 85
WyMuT_CoCHa Avatar answered Sep 23 '22 04:09

WyMuT_CoCHa