Skip to main content

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

Project description

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 messy AI outputs. It handles markdown fences, surrounding text, malformed JSON, and more.

Features

  • Fast: Uses orjson for 10x faster JSON parsing
  • Reliable: Multiple extraction strategies with automatic fallback
  • Smart Repair: Fixes common AI JSON errors (trailing commas, single quotes, unquoted keys)
  • 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```')

Auto-Repair Malformed JSON

# Trailing commas (common AI error)
data = extract_json('{"items": [1, 2, 3,],}')
# Returns: {'items': [1, 2, 3]}

# Single quotes (Python-style)
data = extract_json("{'key': 'value'}")
# Returns: {'key': 'value'}

# Unquoted keys (JavaScript-style)
data = extract_json('{key: "value"}')
# Returns: {'key': 'value'}

Multiple JSON Blocks

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

# Get largest JSON
data = extract_json('{"a": 1} and {"b": 2, "c": 3}', strategy="largest")
# Returns: {'b': 2, 'c': 3}

# 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

Get Extraction Metadata

from ai_extract import extract_json_with_metadata

result = extract_json_with_metadata('```json\n{"key": "value"}\n```')

print(result.success)        # True
print(result.data)           # {'key': 'value'}
print(result.confidence)     # 0.95
print(result.method)         # ExtractionMethod.MARKDOWN_FENCE
print(result.repairs_applied)  # []

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, *, repair=True, strategy="first", raise_on_error=True)

Extract JSON from text.

Parameters:

  • text (str): Text containing JSON
  • repair (bool): Enable auto-repair of malformed JSON (default: True)
  • strategy (str): How to handle multiple JSON blocks
    • "first": Return first valid JSON (default)
    • "largest": Return largest JSON structure
    • "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

extract_json_with_metadata(text, *, repair=True, strategy="first")

Extract JSON with detailed metadata.

Returns: ExtractResult with fields:

  • success (bool): Whether extraction succeeded
  • data (Any): Parsed JSON data
  • raw_json (str): Raw JSON string before parsing
  • confidence (float): Confidence score (0.0-1.0)
  • method (ExtractionMethod): How JSON was found
  • repairs_applied (list[str]): List of repairs performed
  • candidates_found (int): Number of JSON candidates found
  • error (ExtractError): Error details if failed

Extraction Methods

The library tries multiple strategies in order:

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

Repair Strategies

Safe repairs applied automatically:

  • Remove trailing commas
  • Convert single quotes to double quotes
  • Quote unquoted keys
  • Remove BOM and invisible characters
  • Complete truncated JSON (marked in metadata)

License

MIT License - see LICENSE for details.

Author

Rahul Vishwakarma (@rvv-karma)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ai_extract-0.0.3.tar.gz (25.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ai_extract-0.0.3-py3-none-any.whl (15.1 kB view details)

Uploaded Python 3

File details

Details for the file ai_extract-0.0.3.tar.gz.

File metadata

  • Download URL: ai_extract-0.0.3.tar.gz
  • Upload date:
  • Size: 25.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for ai_extract-0.0.3.tar.gz
Algorithm Hash digest
SHA256 217640f82b8eae3e42f9384148bb737a01c53e8e06a99b3d50fab97897d349ea
MD5 69ba7e6189770e66c535b7beffb30b18
BLAKE2b-256 ac7b75346e172124b81c0f93fc1bb5010bdaf2155220f7f79d40b7cebf7a4c13

See more details on using hashes here.

File details

Details for the file ai_extract-0.0.3-py3-none-any.whl.

File metadata

  • Download URL: ai_extract-0.0.3-py3-none-any.whl
  • Upload date:
  • Size: 15.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for ai_extract-0.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 07a736e5d8f8cd6b7bfa18c624caad5f5ddf96e9c8207ac638be6df05b0f804a
MD5 5475cc39bf9d22e116a04f4e72f6bf47
BLAKE2b-256 830963dc5d7e572e1c07ee958f83a98e52aee04537a9dfdf9f9ce4e36e13903e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page