• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

REST API Tutorial

  • REST
  • JSON
  • Dark Mode
Home / JSON / JSON with JSONPath

JSON with JSONPath

One of the biggest strengths of XML is XPath, the query-oriented language to query subsections of an XML document. In the same line, JSONPath is a query language for JSON with features similar to XPath. JSONPath is used for selecting and extracting a JSON document’s property values.

To use JSONPath, we will need to include its dependency and then use it.

JSONPath Syntax

A JsonPath expression begins with the dollar sign ($) character, which refers to the root element of a query. The dollar sign is followed by a sequence of child elements, which are separated via dot (code) notation or via the square brackets (code).

The important JSONPath syntax rules are:

  • $ symbol refers to the root object or element.
  • @ symbol refers to the current object or element.
  • . operator is the dot-child operator, which you use to denote a child element of the current element.
  • [ ] is the subscript operator, which you use to denote a child element of the current element (by name or index).
  • * operator is a wildcard, returning all objects or elements regardless of their names.
  • , operator is the union operator, which returns the union of the children or indexes indicated.
  • : operator is the array slice operator, so you can slice collections using the syntax [start:end:step] to return a subcollection of a collection.
  • ( ) operator lets you pass a script expression in the underlying implementation’s script language. It’s not supported by every implementation of JSONPath, however.
  • ? ( ) to query all items that meet a certain criteria.

Example: JSONPath Expressions

$.store.book[0].title
$.store.book[*].title
$..book[3]

//or using brackets

$['store']['book'][0].['title']
$['store']['book'][*].['title']
$..['book'][3]

$.store.book[?(@.price < 10)].title

JSONPath Example

We have the following JSON document. We will apply the JSONPath expressions on it.

{ "store": {
    "book": [ 
        { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
        { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
        { "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
        { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}

Example 1

Using JSONPath to find the names of all authors.

var response = jsonPath(store , "$..author").toJSONString();

Program output:

[  
   "Nigel Rees",
   "Evelyn Waugh",
   "Herman Melville",
   "J. R. R. Tolkien"
]

Example 2

Using JSONPath to find the details for book number 4. The array index is zero-based.

var response = jsonPath(store , "$..book[3]").toJSONString();

Program output:

[  
   {  
      "category":"fiction",
      "author":"J. R. R. Tolkien",
      "title":"The Lord of the Rings",
      "isbn":"0-395-19395-8",
      "price":22.99
   }
]

JSONPath Dependencies

LanguageDependency
JavaScriptJSONPath JavaScript File
Nodenpm install JSONPath
PHPJSONPath PHP include file
Pythonpip install jsonpath-rw
Java
<dependency>
	<groupId>com.jayway.jsonpath</groupId>
	<artifactId>json-path</artifactId>
	<version>2.0.0</version>
</dependency>

Was this article helpful?

Share this:

  • Twitter
  • Facebook
Previous Tutorial:
JSON with Ajax
Next Tutorial:
JSON Schema

Reader Interactions

Comments

  1. Sachin Gainewar says

    May 11, 2020 at 11:51 am

    $.store.book[?(@.price < 10)].title

    above line Throws an error of :-
    "org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: Script60.groovy: 93: expecting EOF, found '[" @ line 93, column 27. log.info $.store.book[?(@.price < 10)].title ^ org.codehaus.groovy.syntax.SyntaxException: expecting EOF, found '[' @ line 93, column 27. at org.codehaus.groovy.antlr.AntlrParserPlugin.transformCSTIntoAST(AntlrParserPlugin.java:143)

    I am using groovy script in soupui editor

    Kindly correct me

    Reply
  2. Abhineet says

    December 17, 2019 at 3:13 am

    public static List readJsonFileDynamic(String filePath, String jsonPath) {
    	
    	System.out.println("jsonpath - "+jsonPath);
    	try 
    	{
    		String content = new String(Files.readAllBytes(Paths.get(filePath)));
    		Configuration conf = Configuration.builder()
    	            .jsonProvider(new GsonJsonProvider())
    	            .mappingProvider(new GsonMappingProvider())
    	            .build();
    	
    		DocumentContext context = JsonPath.using(conf).parse(content);
    		categories = context.read(jsonPath, List.class);//List 
    		
    	} catch (IOException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	} 
    	return categories;
    }
    Reply
  3. kiruba says

    November 8, 2019 at 9:55 am

    This looks like the original passport JSON data. Please remove it as it violates the person’s privacy.

    Reply
  4. Noha says

    November 3, 2019 at 9:47 am

    Can i use jsonpath in url encoding?

    Reply
  5. Teja says

    September 27, 2019 at 2:25 am

     
    [
      {
        "firstName": "F1",
        "lastName": "L1",
        "address": [
          {
            "city": "Atlanta",
            "country": "US"
          },
          {
            "city": "Maidson",
            "country": "US"
          }
        ]
      },
      {
        "firstName": "F2",
        "lastName": "L2",
        "address": [
          {
            "city": "Nashville",
            "country": "US"
          },
          {
            "city": "Vegas",
            "country": "US"
          }
        ]
      },
      {
        "firstName": "F3",
        "lastName": "L3",
        "address": [
          {
            "city": "Minneapolis",
            "country": "US"
          },
          {
            "city": "Nashville",
            "country": "US"
          }
        ]
      }
    ]
    

    From the above data, how can I get person details who lived in Nashville for example. I am expecting the following result

     
    [
      {
        "firstName": "F2",
        "lastName": "L2",
        "address": [
          {
            "city": "Nashville",
            "country": "US"
          },
          {
            "city": "Vegas",
            "country": "US"
          }
        ]
      },
      {
        "firstName": "F3",
        "lastName": "L3",
        "address": [
          {
            "city": "Minneapolis",
            "country": "US"
          },
          {
            "city": "Nashville",
            "country": "US"
          }
        ]
      }
    ]
    

    Thank you!

    Reply
    • ksk says

      November 1, 2019 at 1:42 pm

      $.[?(@.city=="Nashville")]^^^^

      Looks like this is working fine.

      Reply
  6. Rahul says

    September 25, 2019 at 11:10 am

    Can i transform the json string into another format. I want the JSON string to be transform into array of array where property name in book becomes the column names. ?

    Reply
  7. Sai says

    July 11, 2019 at 3:05 pm

    Can i write regular expression to match the string in javascript. i saw it working in jay way which is for java but in javascript its not working.

    Reply
    • Admin says

      July 11, 2019 at 4:23 pm

      Yes, string.match(regex) takes regular expression in javascript.

      Reply
  8. nshah says

    February 21, 2019 at 11:06 am

    How do I write back to json file using JSONPath ?

    Reply
    • John says

      September 3, 2019 at 5:32 pm

      nshah I don’t think it is possible to write json elements using JSONPath. Otherwise, it would surely be listed on this page.

      Reply
  9. Test says

    February 12, 2019 at 6:58 am

    {
          "kind": "storage#policy",
          "resourceId": "test1",
          "bindings": [
           {
              "role": "roles/admin",
              "members": ["allUsers"]
           },
           ]
    }

    How can I check if members contains ‘allUsers’

    Reply
    • Admin says

      February 12, 2019 at 7:40 am

      Create XPath expression with help of information given in this xpath example.

      Reply
    • Kanchan says

      September 27, 2020 at 2:45 pm

      $•[?(@.members==”allUsers”]

      Reply
  10. sarika says

    November 16, 2018 at 7:24 am

    How can i append two string response from json using jsonpath ?
    Ex. JsonResponse

    {
    "passport": {
            "page_1": {
                "passport_number": "xxxxxxx",
                "photo": "https://storage.googleapis.com/dolphin-ekyc-api-v2/2018-11-15-xxxx.jpeg",
                "sign": "https://storage.googleapis.com/dolphin-ekyc-api-v2/2018-11-15-xxxx.jpeg",
                "surname": "RAMADUGULA",
                "name": "SITA MAHA LAKSHMI",
                "nationality": "INDIAN",
                "sex": "",
                "date_of_birth": "23/09/xxxx",
                "place_of_birth": "GUNDUGOLANU",
                "date_of_issue": "11/10/xxxx",
                "date_of_expiry": "10/10/xxxx"
            }
    }
    }

    I just want to append name and surname like SITA MAHA LAKSHMI RAMADUGULA.

    When i tried using $['passport']['page_1']['name','surname'] its giving me value :

    {
       "name" : "SITA MAHA LAKSHMI",
       "surname" : "RAMADUGULA"
    }

    that i don’t want. Any idea about it ??

    Reply
    • Debi says

      November 26, 2018 at 12:53 pm

      $.passport.page_1.(name & ' ' & surname)

      Result : “SITA MAHA LAKSHMI RAMADUGULA”

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Search Tutorials

JSON Tutorial

  • What is JSON
  • JSON Syntax
  • JSON Data Types
  • JSON Schema
  • JSON Object
  • JSON Array
  • JSON parse()
  • JSON stringify()
  • JSON vs XML
  • JSON with Ajax
  • JSONPath

Footer

References

  • The dissertation by Roy Thomas Fielding
  • Uniform Resource Identifier (URI, URL, URN) [RFC 3986]
  • Internet MediaTypes
  • Web Application Description Language (WADL)

Meta Links

  • About
  • Contact Us
  • Privacy Policy

Blogs

  • How To Do In Java

Copyright © 2020 · restfulapi.net · All Rights Reserved. | Sitemap