JSONPath in Python How to Parse With Examples

Are you looking for ways to parse JSON in Python? In this article, I will discuss how you can use JSONPath in Python to parse the JSON in your application.

JSON (JavaScript Object Notation)[1] is the data format to exchange data in a most efficient way keeping it easy to read and write. It is human-readable text that stores the information and is very easy to transmit with the use of JavaScript Data Object.

What is JSONPath in Python?

JSONPath is a syntax for parsing JSON data. It is extremely similar to the XPath expression language, which is used to parse XML data.

The goal is to parse the JSON input and extract the desired value. This is more memory efficient, as we are not reading the entire JSON data.

Types of JSONPath Library Present in Python

There are currently three different types of JSONPath libraries in Python. Below is the list of three different JSONPath libraries that you can use to parse JSON in your Python application.

  1. jsonpath: This is a port of JSONPath’s Perl and JavaScript versions. This one is the most initial version of the port and has lesser features and documentations available to use.
  2. jsonpath-rw: A comprehensive implementation of JSONPath expressions in Python. JSONPath expressions are first-class objects that can be easily analyzed, transformed, parsed, printed, and extended. The jsonpath-rw-ext module includes several extensions that extend the module’s functionality. This library has some additional features and omits some of the problematic features of the full version available for Python.
  3. jsonpath-ng: The final implementation of the JSONPath, which includes arithmetic and binary comparison operators. This library unifies and enhances the jsonpath-rw and jsonpath-rw-ext modules.

List of JSONPath Operators:

Below is the list of operators you can use for getting JSON data values using JSONPath.

SyntaxMeaning
jsonpath1.jsonpath2All nodes matched by jsonpath2 starting at any node matching jsonpath1
jsonpath[whatever]Same as jsonpath.whatever
jsonpath1 .. jsonpath2All nodes matched by jsonpath2 that descend from any node matching jsonpath1
jsonpath1 where jsonpath2Any nodes matching jsonpath1 with a child matching jsonpath2
jsonpath1|jsonpath2Any nodes matching the union of jsonpath1 and jsonpath2

Best Python JSONPath Library to Use?

The most thorough module is jsonpath-ng, which is built entirely in Python. It is compatible with both Python 2 and Python 3.

But you can also use the json-rw library as this one is the most refined library and I will use this module for Python JSONPath examples.

Installing JSONPath-rw Module

You can install JSONPath-rw using the PIP installer. Go to the command prompt or the terminal and type the below command.

Make sure you have pip installed on your system along with Python. Else use this script to install pip on your system.

$ pip install jsonpath-rw

JSONPath in Python How to Parse With Examples

Parsing a Simple JSON Data using JSONPath

Let’s start using the above-installed library and parse a sample JSON data using this library to understand how it works.

import json
from jsonpath_rw import jsonpath, parse

stringWithJsonData = '{"EmployeeList": [{"Name": "Jaime", "id":123}, {"Name": "Sanya", "id":124}]}'

getJsonData = json.loads(stringWithJsonData)

jsonExpression = parse('$.EmployeeList')

getMatch = jsonExpression.find(getJsonData)

print(getMatch[0].value)
print("The Employee Id of Sanya is " + str(getMatch[0].value[1]['id']))

Output:

[{'Name': 'Jaime', 'id': 123}, {'Name': 'Sanya', 'id': 124}]
The Employee Id of Sanya is 124

Conclusion

JSONPath simplifies the process of parsing JSON input and extracting specified values. It’s extremely beneficial when the JSON data is large and we’re only interested in a few values.

That is all for this post, let me know if you have any questions in the comment section and let me know if you want a mode example for the above JSONPath library.

Please follow us on Facebook and Twitter. We will be soon coming with Free Courses on Python on all the topics such as Beginner, Intermediate, and Advance. Keep following us for further updates.

Further Read:

  1. How To Select All Columns Except One Column in Pandas
  2. How To Iterate Over Rows in a DataFrame in Pandas Python
  3. Python Get Filename From A Path Without Extension 4 Ways

Leave a Comment