Search code examples
spring-testjsonpath

how to escape [ ] in jsonPath


How can I escape square brackets in a JSONPath matcher?

.andExpect(jsonPath("$.fieldErrors.addresses[0].contactAddress1", Matchers.any(String.class)))

doesn't match, even though the JSON exists, and I think it's because of the square brackets.

"{\"errors\":[],\"fieldErrors\":{\"adminName\":\"Admin Name is a required field\",\"addresses[0].contactCompany\":\"Company is a required field\",\"addresses[0].contactAddress1\":\"Address is a required field\",\"addresses[0].contactPhoneNumber\":\"Phone Number cannot exceed 25 characters\"},\"uiMessageClass\":null,\"uiMessage\":null,\"redirectUrl\":null,\"object\":null}"

Is there a way to escape the brackets?


Solution

  • fieldErrors does not contain a property named addresses that is an array or list. Thus you are using the wrong syntax.

    Have you tried simply quoting the name of the property like this?

    .andExpect(jsonPath("$.fieldErrors['addresses[0].contactAddress1']", Matchers.any(String.class)))
    

    For further details, consult the official JsonPath documentation.

    I also tried out your additional failing test that you discuss in the comments, but I cannot reproduce the problem. For example, the following test passes fine for me:

    @Test
    public void test() {
        String input = "{\"errors\":[],\"fieldErrors\":{\"labels[en]\":\"Label is a required field\",\"externalIdentifier\":\"Identifier is a required field\"},\"uiMessageClass\":null,\"uiMessage\":null,\"redire‌​ctUrl\":null,\"objec‌​t\":null}";
        JsonPathExpectationsHelper jsonPath = new JsonPathExpectationsHelper("$.fieldErrors['labels[en]']");
        jsonPath.exists(input);
        jsonPath.assertValue(input, Matchers.any(String.class));
        jsonPath.assertValue(input, "Label is a required field");
    }
    

    Regards,

    Sam