educative.io

Can you add more examples of parsing json using JsonPath

I am confused about the syntax json query has and the ones you used to demonstrate
for example, syntax has this “$…city”
but nothing like $(dollar sign), or wildcard characters are used in example


Course: Learn REST and SOAP API Test Automation in Java - Learn Interactively
Lesson: JSONPath Library - Learn REST and SOAP API Test Automation in Java

Hi @Atul
Let’s clarify the syntax:

  1. $…city: This expression selects all elements with the key “city” at any level of the JSON structure. The “$” denotes the root of the JSON document, and “…” signifies a recursive search, so it will find all occurrences of “city” regardless of where they are nested in the JSON.

  2. $.address.*: This selects all elements under the “address” key. The “*” is a wildcard operator that matches any field name under “address”.

  3. $.address…zipCode: This selects all “zipCode” elements under the “address” key, again using recursive descent to search all levels of the JSON.

  4. $.address[1]: This selects the second address element under the “address” key. The indexing starts at 0, so [1] selects the second element.

  5. $…address[:2]: This selects all address elements up to the second one (exclusive). It’s using array slicing, where the slice notation [:2] means from the start to index 2 (exclusive).

  6. $…address[1:]: This selects all address elements starting from the second one to the end. The [1:] slice notation selects elements from index 1 to the end of the array.

  7. $…address[?(@.city)]: This selects all address elements that have a “city” key. The filter expression “?(@.city)” checks if each address object has a “city” field.

Regarding the absence of the “$” or wildcard characters in the Java code example, it’s because the Java code interacts with the JSON using the JSONPath library directly, which abstracts away the need to explicitly use these symbols in the code. The library handles the parsing and querying of the JSON data based on the provided expressions. So, even though you don’t see “$” or wildcards in the Java code, they are implicitly understood by the library when you provide the JSONPath expressions.
I hope it helps. Happy Learning :blush: