JSONPath is an expression language and JSONPath Python is a way to parse JSON data. JSONPath provides a simpler syntax to query JSON data and get the desired value in Python. There are many JSONPath libraries for Python. JSON stands for JavaScript Object Notation. JSONPath in Python is similar to the XPath in XML.

In this article, we will learn how to use JSONPath for Python along with the use of the JSONPath libraries.

How To Use JSONPath In Python

There are many JSONPath libraries in Python. Some of the popular JSONPath libraries are jsonpath-rw, jsonpath-rw-ext, and jsonpath-ng and the most popular one is the jsonpath-ng library. Let us learn how to use JSONPath for Python.

Let’s start by installing the jsonpath-ng library using Python’s Package Manager (pip). To install the jsonpath-ng library, run the following command in our terminal:

pip install jsonpath-ng

You can then import jsonpath-ng in Python using a Python IDE with the following code:

import jsonpath_ng

JSONPath Python Example

Here’s an example of how JSONPath can be used in Python to work with JSON data:

import json
from jsonpath_ng import jsonpath, parse

booksData = ‘{“Category”:”Finance”, “Author”:”Bibek dai” , “Title”:”The blogger’s page”}’
Data = json.loads(booksData)
ParseData= parse(‘$.Category’)
Category = ParseData.find(Data)
ParseData1= parse(‘$.Author’)
Author = ParseData1.find(Data)
ParseData2= parse(‘$.Title’)
Title = ParseData2.find(Data)

print(“The Category of the book is: “, Category[0].value)
print(“The Author of the book is: “, Author[0].value)
print(“The Name of the book is: “, Title[0].value)

The output will be:
The Category of the book is: Finance
The Author of the book is: Bibek Dai
The Name of the book is: The Blogger’s page

JSONPath Python Syntax

JSONPath operators:

Syntax Meaning
jsonpath1 . jsonpath2 All nodes that are matched by jsonpath2 starting at any node matching jsonpath1
jsonpath [ whatever ] Same as jsonpath.whatever
jsonpath1 .. jsonpath2 All nodes that are matched by jsonpath2 that descend from any node matching jsonpath1
jsonpath1 where jsonpath2 Any nodes matching jsonpath1 with a child matching jsonpath2
jsonpath1 | jsonpath2 Any nodes matching the union of jsonpath1 and jsonpath2

Leave a comment

Your email address will not be published.