Saturday, October 30, 2021

ItsMyCode: Python JSONPath

ItsMyCode |

JSONPath is an expression language that is used to parse the JSON data in Python. JSONPath is similar to XPath in XML, where we parse the XML data. 

JSONPath provides a simpler syntax to query JSON data and get the desired value in Python. Using JSONPath will be the more efficient way to parse and query JSON data as we don’t have to load the entire JSON data. This approach is more memory-optimized compared to any other way of querying JSON.

JSONPath Library in Python

There are many JSONPath libraries for Python, and the most popular one is the jsonpath-ng library. It’s written in the native Python language and supports both Python 2 and Python 3 versions.

jsonpath-ng is the final implementation of JSONPath for Python that aims for standard-compliant including arithmetic and binary comparison operators s, as defined in the original JSONPath proposal.  

This packages merges both jsonpath-rw and jsonpath-rw-ext and provides several AST API enhancements, such as the ability to update or remove nodes in the tree.

Installing jsonpath-ng Module

To install jsonpath-ng library, use the below pip install command. 

pip install --upgrade jsonpath-ng

The above command will install the latest version of the jsonpath-ng library on your machine. Once installed, you can import in the Python IDE using the below code.

import jsonpath_ng

Jsonpath operators:

Below are the list of operators you can use for getting json data values.

Syntax Meaning
jsonpath1 . jsonpath2 All nodes matched by jsonpath2 starting at any node matching jsonpath1
jsonpath [ whatever ] Same as jsonpath.whatever
jsonpath1 .. jsonpath2 All nodes 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

Parsing a Simple JSON Data using JSONPath

A Simple example of parsing the JSON and fetching the JSON value using the attribute key.

# Program to parse JSON data in Python 
import json
from jsonpath_ng import jsonpath, parse

employee_data = '{"id":1, "first_name":"Chandler" , "last_name":"Bing"}'
json_data = json.loads(employee_data)

jsonpath_expr= parse('$.first_name')
first_name = jsonpath_expr.find(json_data)

print("The First Name of the employee is: ", first_name[0].value)

Output

The First Name of the employee is  Chandler

Parsing a Json Array using JSONPath Expression

The JSON key contains the list of values and uses the JSON Path expression. We can parse and query the exact field values of the JSON.

{
    "books": [
        {
            "category": "reference",
            "author": "Nigel Rees",
            "title": "Sayings of the Century",
            "isbn": "6-246-2356-8",
            "price": 8.95
        },
        {
            "category": "fiction",
            "author": "Evelyn Waugh",
            "title": "Sword of Honour",
            "isbn": "5-444-34234-8",
            "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
        }
    ]
}

In the above JSON data, if we need the list of all ISBN of the book, we can use the below code to get the data using JSONPath expression as shown below.

# Program to parse JSON data in Python 
import json
from jsonpath_ng import jsonpath, parse

with open("books.json", 'r') as json_file:
    json_data = json.load(json_file)

jsonpath_expression = parse('books[*].isbn')

for match in jsonpath_expression.find(json_data):
    print(f'Books ISBN: {match.value}')


Output

Books ISBN: 6-246-2356-8
Books ISBN: 5-444-34234-8
Books ISBN: 0-553-21311-3
Books ISBN: 0-395-19395-8

The post Python JSONPath appeared first on ItsMyCode.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...