# JsonPath

[https://www.pluralsight.com/blog/tutorials/introduction-to-jsonpath](https://www.pluralsight.com/blog/tutorials/introduction-to-jsonpath)

[https://github.com/json-path/JsonPath](https://github.com/json-path/JsonPath)

[https://support.smartbear.com/alertsite/docs/monitors/api/endpoint/jsonpath.html](https://support.smartbear.com/alertsite/docs/monitors/api/endpoint/jsonpath.html)

JSONPath is a query language for JSON, similar to XPath for XML

## 1. Maven dependency

```markup
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.1.0</version>
</dependency>
```

## 2. Functions and Filters

JsonPath also has functions that can be used to the end of a path to synthesize that path's output expressions: min(), max(), avg(), stddev(), length().

Finally - we have filters; these are boolean expressions to restrict returned lists of nodes to only those that calling methods need.

A few examples are equality (==), regular expression matching(=\~), inclusion(in), check for emptiness(empty),. Filters are mainly used for predicates.

For a full list and detailed explanations of different operates, functions and filters, please refer to JsonPath GitHub project.

## 3 examples: JsonPath.with()

```java
    @Then("^These two item's quantity are reset by weight and default$")
    public void oneWeightOneDefaultItem() throws Throwable{
        logger.info("\n" + "***Reset the quantity based on weight and default tareWeight");
        try{

            expectedResponseBody = ResponseHandler.prepareTareWeightAndDefaultResponse();

            float expectQuantity0 = JsonPath.with(expectedResponseBody).get("items[0].quantity");
            float actualQuantity0 = JsonPath.with(actualResponseBody).get("items[0].quantity");
            float expectQuantity1 = JsonPath.with(expectedResponseBody).get("items[1].quantity");
            float actualQuantity1 = JsonPath.with(actualResponseBody).get("items[1].quantity");

            boolean a = expectQuantity0==actualQuantity0;
            boolean b = expectQuantity1==actualQuantity1;
            Assert.assertTrue(a&b);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
```

## 4. examples: read:

```java
@Test
public void givenStarring_whenRequestingMovieTitle_thenSucceed() {
    List<Map<String, Object>> dataList = JsonPath.parse(jsonString)
      .read("$[?('Eva Green' in @['starring'])]");
    String title = (String) dataList.get(0).get("title");

    assertEquals("Casino Royale", title);
}
```
