1

I have Java application which gets JSON strings like this one

{
    "name": "testName",
    "message": [
        "TestMessage."
    ]
}

What I need is to check if there is a "message" array node which has value of "TestMessage." in any of it's elements.

I have access to com.jway.jsonpath.JsonPath in my code. But it looks that it can only read value of particular node. E.g. like this I will be able to fetch first element of "message" array

JsonPath.read(content, "$.message[0]")

But in this way I will have to fetch all elements of the array into Java and validate them there. Instead I would like to perform this check by JsonPath engine itself.

How can I achive this goal with JsonPath? Is it better to use other library?

1 Answer 1

4

You can use the filter operations.

Filters are logical expressions used to filter arrays. A typical filter would be [?(@.age > 18)] where @ represents the current item being processed. More complex filters can be created with logical operators && and ||. String literals must be enclosed by single or double quotes ([?(@.color == 'blue')] or [?(@.color == "blue")]).

like this:

 JsonPath.read(json, "$.message[?(@ == "TestMessage.")]");

more can refer the readme.MD of https://github.com/json-path/JsonPath

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the answer. I can see it works here jsonpath.herokuapp.com. But it does not work in my app and here jsonpath.curiousconcept.com. The verion of json-path I am using is 2.0.0. Do you know if I should use any specific version? Or what can be the reason why it is not working?
Ok, I switched to latest jway version which is 2.4.0 at it works now. Thanks a lot for help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.