Search code examples
jsonpathjson-path-expression

Jsonpath how to select this json with inner json node


Jsonpath is new for me and I am leaning this. I can only select the name as $.name. I don't know how to select employeename and type from this json? Could someone tell me how?

{

"name": "{\r\n  \"employeename\": \"Test  name\"\r\n}\r\n",

" availability": {

    "available": true,

    "type": "private"

},

"is_available": true
}

Solution

  • This code would be:

    @Test
    void SO_69565621() throws JsonProcessingException {
        String text = "{\n" +
                "  \"name\": \"{\\r\\n  \\\"employeename\\\": \\\"Test  name\\\"\\r\\n}\\r\\n\",\n" +
                "  \" availability\": {\n" +
                "    \"available\": true,\n" +
                "    \"type\": \"private\"\n" +
                "  },\n" +
                "  \"is_available\": true\n" +
                "}";
        String name = JsonPath.read(text, "$.name");
        JsonNode jsonNode = new ObjectMapper().readTree(name);
        MatcherAssert.assertThat(jsonNode.get("employeename").asText(), Matchers.is("Test  name"));
    }
    

    I'm using Jackson to convert String to JsonNode, then get value of this JsonNode.

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.12.4</version>
    </dependency>