Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JsonPath cannot create a new path if doesn't exists #570

Open
pyus13 opened this issue Oct 10, 2019 · 2 comments
Open

JsonPath cannot create a new path if doesn't exists #570

pyus13 opened this issue Oct 10, 2019 · 2 comments

Comments

@pyus13
Copy link

pyus13 commented Oct 10, 2019

Eg the Json is

val myJson = "properties" : {
}

val json = JsonPath.parse(myJson).set("$.properties.image.source", "my_image_url").jsonString()

Log.d("", "JSON UPDATED $json")

returns

"properties" : {
}

instead of

"properties" : {
    "image" :{
        "source" : "my_image_url" 
    }
}

The test method in Kotlin.

 @Test
 fun testJsonPathSet() {
        val jsonString = "{\"properties\": {}}"
        val newJson = JsonPath.parse(jsonString).set("$.properties.image.source", "image_url").jsonString()
        val expectedNewJson = "{\"properties\":{\"image\":{\"source\":\"image_url\"}}}"
        Assert.assertEquals(expectedNewJson, newJson)
    }
@pyus13 pyus13 changed the title JsonPath cannot create path if not exists JsonPath cannot create a new path if doesn't exists Oct 10, 2019
@Alanscut
Copy link
Contributor

Alanscut commented Jan 9, 2020

@pyus-13 set function only could change the value whith the path exists. If you want to add a new path, you could use put function to achive it.
In your case, you could write like this:

    String json = "{\"properties\": {}}";
    DocumentContext context = JsonPath.parse(json);

    context.put("$.properties", "image", new HashMap<>());   // add a new path "$.properties.image"
    context.put("$.properties.image", "source","image_url"); // continue to add a new path "$.properties.image.source"
    String newJson = context.jsonString();
    String expectedNewJson = "{\"properties\":{\"image\":{\"source\":\"image_url\"}}}";

    Assert.assertEquals(expectedNewJson, newJson);

@drekbour
Copy link

Dupe #83

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants