2

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
}
Masi Boo
  • 635
  • 1
  • 10
  • 24
  • Value of key `name` is string, not json object, you can't use jsonpath to extract `employeename`. You have to covert this string `"{\r\n \"employeename\": \"Test name\"\r\n}\r\n"` to json object first, then extract data later. – lucas-nguyen-17 Oct 14 '21 at 08:12
  • Just tried https://jsonlint.com/ and it is Valid JSON. – Masi Boo Oct 14 '21 at 10:32
  • Please re-read my comment, I didn't say your json is not valid, I said "Value of key `name` is string, not json object" --> can use jsonpath for this. – lucas-nguyen-17 Oct 14 '21 at 10:53
  • Yes if I do $.name I get `\r\n \"employeename\": \"Test name\"\r\n`. But i want select only `employeename` and try to get value as `Test name` – Masi Boo Oct 14 '21 at 13:04
  • As I said, you have to convert this string to json object first, then extract it. What language do you use? – lucas-nguyen-17 Oct 14 '21 at 13:09
  • I am using Java 8 and in the Junit test as:- `givenValidRequest(Country.SWEDEN, Language.SE) .when() .get(vaseUrl + "/book/empolyee") .then() .log().everything() .statusCode(HttpStatus.OK.value()) .contentType(MediaType.APPLICATION_JSON_VALUE) .body("name", is(\\r\\n \\\employeename\\\": \\\"Test name\\\\\r\\n)) // error.` How can do it? – Masi Boo Oct 14 '21 at 13:52
  • Junit assertion error `java.lang.AssertionError: 1 expectation failed. JSON path name doesn't match. Expected: is \\r\\n \\\employeename\\\": \\\"test Name\\\\\r\\n Actual: { "employeename": "test Name" }` – Masi Boo Oct 14 '21 at 14:12

1 Answers1

1

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>
lucas-nguyen-17
  • 5,516
  • 2
  • 9
  • 20