Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonPath JUnit escape character for dots

I have a json field which is called template.welcome.email and I am writing a unit test that checks if that field is present in the reply from the server but I can't find an escape for the dots in the name of the field. The code of my test is :

@Test
public void testEmailTemplates() throws Exception {     
    mockMvc.perform(get("/emailTemplates")
        .contentType(MediaType.APPLICATION_JSON)
        .locale(Locale.UK)
        .accept(MediaType.APPLICATION_JSON))

        .andDo(print())
        .andExpect(status().isOk())

        .andExpect(jsonPath("$.template.welcome.email").exists())

        .andExpect(redirectedUrl(null))
        .andExpect(forwardedUrl(null));
}

But I get the following exception, because the dots are interpreted like paths:

java.lang.AssertionError: No value for JSON path: $.template.welcome.email, exception: invalid path
at org.springframework.test.util.JsonPathExpectationsHelper.evaluateJsonPath(JsonPathExpectationsHelper.java:74)
at org.springframework.test.util.JsonPathExpectationsHelper.exists(JsonPathExpectationsHelper.java:121)
at org.springframework.test.web.servlet.result.JsonPathResultMatchers$3.match(JsonPathResultMatchers.java:77)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:141)
at 

Do you know any escape character for the jsonPath?

like image 933
cloudy_weather Avatar asked Nov 01 '13 12:11

cloudy_weather


3 Answers

Use brackets and quotes around your field. For example, if your field is valid.key.with.dot

Refer to it as ['valid.key.with.dot'] and in JsonPath, try

JsonPath.read(jsonString, "$.['valid.key.with.dot']") 

See this thread also: https://groups.google.com/forum/#!topic/jsonpath/7YvgXWP1_7Y

like image 123
Ida Avatar answered Sep 20 '22 01:09

Ida


As Ida pointed out:

Use brackets and quotes around your field. For example, if your field is valid.key.with.dot

Refer to it as ['valid.key.with.dot'] and in JsonPath, try

JsonPath.read(jsonString, "$.['valid.key.with.dot']")

like image 42
Roman Konoval Avatar answered Sep 20 '22 01:09

Roman Konoval


These days (e.g. io.rest-assured.json-path:3.0.1) the notation seems to be without brackets:

// Some Groovy OData V4 $count test
// Response looks like:
// { "@odata.count": 2, ... }
body "'@odata.count'", equalTo(2)

I found the corresponding hint in this Git issue.

like image 25
Michael Jess Avatar answered Sep 21 '22 01:09

Michael Jess