pyjq - Python Binding for jq

2.6.0 · active · verified Fri Apr 17

pyjq is a Python binding for the `jq` command-line JSON processor. It allows executing `jq` queries against Python dictionaries and lists, providing flexible and powerful JSON data manipulation capabilities. As of version 2.6.0, it primarily offers a `jq()` function with options for single or multiple results, as well as a `run()` function for CLI-like behavior. It is actively maintained with regular updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `pyjq.jq()` to query Python dictionaries, including how to handle multiple results with `all_results=True`. It also shows `pyjq.run()` for processing raw JSON string inputs, mimicking the `jq` CLI.

import pyjq
import json

data = {
    "items": [
        {"name": "Apple", "price": 1.0, "category": "Fruit"},
        {"name": "Banana", "price": 0.5, "category": "Fruit"},
        {"name": "Carrot", "price": 0.3, "category": "Vegetable"}
    ]
}

# Select names of all fruits, returning a list of results
fruit_names = pyjq.jq('.items[] | select(.category == "Fruit") | .name', data, all_results=True)
print(f"Fruit names: {list(fruit_names)}")

# Get the price of the first item (returns an iterator by default)
# Use next() to get the first value from the iterator
first_item_price_iterator = pyjq.jq('.items[0].price', data)
print(f"First item price (iterator): {next(first_item_price_iterator)}")

# Using pyjq.run for CLI-like behavior, processing a JSON string
json_string = json.dumps(data)
all_prices_iterator = pyjq.run('.items[].price', text_input=json_string)
print(f"All prices (from string input): {list(all_prices_iterator)}")

view raw JSON →