Skip to main content

ai-extract

Extract structured data from any AI response. Fast. Simple. Reliable.

PyPI version Python 3.9+ License: MIT

ai-extract is a fast, lightweight Python library for extracting JSON from AI outputs. It handles markdown fences, surrounding text, and multiple JSON blocks.

Features

  • Fast: Uses orjson for 10x faster JSON parsing
  • Reliable: Multiple extraction strategies with automatic fallback
  • Simple API: One function for most use cases
  • CLI Tool: Quick extraction from command line
  • Zero Config: Works out of the box

Installation

pip install ai-extract

Quick Start

from ai_extract import extract_json

# Extract from messy AI output
text = """
Here's the JSON you requested:
```json
{"name": "John", "age": 30}

Hope this helps! """

data = extract_json(text) print(data) # {'name': 'John', 'age': 30}


## Usage Examples

### Basic Extraction

```python
from ai_extract import extract_json

# Pure JSON
data = extract_json('{"key": "value"}')

# JSON in text
data = extract_json('The result is: {"success": true}')

# JSON in markdown fence
data = extract_json('```json\n{"data": [1,2,3]}\n```')

Multiple JSON Blocks

# Get first JSON (default)
data = extract_json('{"a": 1} and {"b": 2}')
# Returns: {'a': 1}

# Get all JSON blocks
data = extract_json('{"a": 1} and {"b": 2}', strategy="all")
# Returns: [{'a': 1}, {'b': 2}]

Error Handling

from ai_extract import extract_json, ExtractError

# Raise exception (default)
try:
    data = extract_json("no json here")
except ExtractError as e:
    print(f"Error: {e.message}")
    print(f"Type: {e.error_type}")

# Return None instead
data = extract_json("no json here", raise_on_error=False)
# Returns: None

CLI Usage

# From argument
ai-extract '{"key": "value"}'

# From file
ai-extract -f response.txt

# From stdin
echo '{"key": "value"}' | ai-extract

# Pretty print
ai-extract -f response.txt --pretty

# Get all JSON blocks
ai-extract -f response.txt --all

# Show metadata
ai-extract -f response.txt --verbose

API Reference

extract_json(text, *, strategy="first", raise_on_error=True)

Extract JSON from text.

Parameters:

  • text (str): Text containing JSON
  • strategy (str): How to handle multiple JSON blocks
    • "first": Return first valid JSON (default)
    • "all": Return list of all JSON blocks
  • raise_on_error (bool): Raise ExtractError on failure (default: True)

Returns: Parsed JSON data, or list if strategy="all", or None if raise_on_error=False

Extraction Methods

The library tries multiple strategies in order:

  1. Direct Parse - Try parsing entire input as JSON
  2. Markdown Fence - Extract from ```json blocks
  3. Brace Matching - Find balanced {...} or [...]
  4. Heuristic - Pattern matching after "Here's the JSON:" etc.

License

MIT License - see LICENSE for details.

Author

Rahul Vishwakarma (@rvv-karma)

Metadata

Release files for ai-extract 0.0.7

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ai-extract 0.0.7
File Size Uploaded Provenance
ai_extract-0.0.7.tar.gz 15.9 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for ai-extract 0.0.7
File Interpreter ABI Platform
ai_extract-0.0.7-py3-none-any.whl Python 3 none any Details

Total release size: 25.8 kB

Release files / ai_extract-0.0.7.tar.gz

Download URL ai_extract-0.0.7.tar.gz
Size 15.9 kB
Tags Source
SHA-256 checksum
How to use checksums
0685c8819dfa2c49a2933f45ff0711b50421be488872f4cbfa99b872d9d9ccdd
BLAKE2b-256 checksum
How to use checksums
58b5e8c977a6f39767fa1147562169e836950384ab93316dc82db1d82ddbf5ac
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.12

Release files / ai_extract-0.0.7-py3-none-any.whl

Download URL ai_extract-0.0.7-py3-none-any.whl
Size 9.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1ed085e1ccd0acd60b579d7cf939eee0617274d84ea6c1fc093b98e901531e8b
BLAKE2b-256 checksum
How to use checksums
207b8969ce54b805d372435af5f093274dde90d61056d44a9e821e6e768bbd38
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.12

Security for ai-extract 0.0.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page