> ## Documentation Index
> Fetch the complete documentation index at: https://praison.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# JSON Agent

> JSON data processing tools for AI agents.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent
from praisonaiagents import read_json, validate_json

agent = Agent(
    name="JSON Assistant",
    instructions="Validate and summarise JSON payloads.",
    tools=[read_json, validate_json],
)
agent.start("Validate config.json and list any schema errors")
```

The user points at JSON data; the agent validates structure and reports issues in plain language.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    U[Input] --> A[Agent]
    A --> T[Tool]
    T --> O[Output]

    classDef agent fill:#8B0000,color:#fff
    classDef tool fill:#189AB4,color:#fff

    class A agent
    class U,O tool
    class T tool
```

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant Agent
    participant Feature as JSON Agent

    User->>Agent: Request
    Agent->>Feature: Process request
    Feature-->>Agent: Result
    Agent-->>User: Response
```

<Note>
  **Prerequisites**

  * Python 3.10 or higher
  * PraisonAI Agents package installed
  * PraisonAI Tools package installed
  * Basic understanding of JSON format
</Note>

## JSON Tools

Use JSON Tools to process and manipulate JSON files with AI agents.

<Steps>
  <Step title="Install Dependencies">
    First, install the required packages:

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    pip install praisonaiagents praisonai-tools
    ```
  </Step>

  <Step title="Import Components">
    Import the necessary components:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent, Task, AgentTeam
    from praisonai_tools import (
        read_json, write_json, merge_json,
        validate_json, analyze_json, transform_json
    )
    ```
  </Step>

  <Step title="Create Agent">
    Create a JSON processing agent:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    json_agent = Agent(
        name="JSONProcessor",
        role="JSON Processing Specialist",
        goal="Process JSON files efficiently and accurately.",
        backstory="Expert in JSON file manipulation and validation.",
        tools=[
            read_json, write_json, merge_json,
            validate_json, analyze_json, transform_json
        ],
        reflection=False
    )
    ```
  </Step>

  <Step title="Define Task">
    Define the JSON processing task:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    json_task = Task(
        description="Parse and validate API response data.",
        expected_output="Validated and processed JSON data.",
        agent=json_agent,
        name="json_processing"
    )
    ```
  </Step>

  <Step title="Run Agent">
    Initialize and run the agent:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    agents = AgentTeam(
        agents=[json_agent],
        tasks=[json_task],
        process="sequential"
    )
    agents.start()
    ```
  </Step>
</Steps>

## Understanding JSON Tools

<Card title="What are JSON Tools?" icon="question">
  JSON Tools provide JSON processing capabilities for AI agents:

  * File reading and writing
  * Data validation
  * Schema validation
  * Data transformation
  * Structure analysis
</Card>

## Key Components

<CardGroup cols={2}>
  <Card title="JSON Agent" icon="user-robot">
    Create specialized JSON agents:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    Agent(tools=[read_json, write_json, merge_json, validate_json, analyze_json, transform_json])
    ```
  </Card>

  <Card title="JSON Task" icon="list-check">
    Define JSON tasks:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    Task(description="json_operation")
    ```
  </Card>

  <Card title="Process Types" icon="arrows-split-up-and-left">
    Sequential or parallel processing:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    process="sequential"
    ```
  </Card>

  <Card title="JSON Options" icon="sliders">
    Customize JSON operations:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    indent=2, sort_keys=True
    ```
  </Card>
</CardGroup>

## Available Functions

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai_tools import read_json
from praisonai_tools import write_json
from praisonai_tools import merge_json
from praisonai_tools import validate_json
from praisonai_tools import analyze_json
from praisonai_tools import transform_json
```

## Function Details

### read\_json(filepath: str, encoding: str = 'utf-8', validate\_schema: Optional\[Dict\[str, Any]] = None)

Reads JSON files with schema validation:

* Optional schema validation
* Custom encoding support
* Error handling

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Basic usage
data = read_json("config.json")

# With schema validation
schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "integer"}
    }
}
data = read_json(
    "user.json",
    encoding="utf-8",
    validate_schema=schema
)

# Returns: Dict[str, Any] (JSON data)
# Error case: Returns dict with 'error' key
```

### write\_json(data: Union\[Dict\[str, Any], List\[Any]], filepath: str, encoding: str = 'utf-8', indent: int = 2, sort\_keys: bool = False, ensure\_ascii: bool = False)

Writes data to JSON files:

* Pretty printing with indentation
* Optional key sorting
* Unicode support
* Directory creation

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Basic usage
data = {"name": "Alice", "age": 30}
success = write_json(data, "output.json")

# With formatting options
data = {
    "users": [
        {"name": "Alice", "age": 30},
        {"name": "Bob", "age": 25}
    ]
}
success = write_json(
    data,
    "users.json",
    indent=4,
    sort_keys=True,
    ensure_ascii=False
)
# Returns: bool (True if successful)
```

### merge\_json(files: List\[str], output\_file: str, merge\_arrays: bool = True, overwrite\_duplicates: bool = True)

Merges multiple JSON files:

* Deep merging of objects
* Array handling options
* Duplicate key handling
* Nested structure support

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Merge configuration files
success = merge_json(
    files=["config1.json", "config2.json"],
    output_file="merged_config.json"
)

# Advanced merge with options
success = merge_json(
    files=["base.json", "override.json"],
    output_file="final.json",
    merge_arrays=True,
    overwrite_duplicates=False
)
# Returns: bool (True if successful)
```

### validate\_json(data: Union\[Dict\[str, Any], str], schema: Dict\[str, Any])

Validates JSON against a schema:

* JSON Schema support
* Detailed error messages
* File or data validation

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Validate data
schema = {
    "type": "object",
    "required": ["name", "email"],
    "properties": {
        "name": {"type": "string"},
        "email": {"type": "string", "format": "email"},
        "age": {"type": "integer", "minimum": 0}
    }
}

# Validate data directly
data = {"name": "Alice", "email": "alice@example.com", "age": 25}
is_valid, error = validate_json(data, schema)

# Validate file
is_valid, error = validate_json("user.json", schema)
# Returns: Tuple[bool, Optional[str]]
```

### analyze\_json(data: Union\[Dict\[str, Any], str], max\_depth: int = 10)

Analyzes JSON structure:

* Type information
* Size metrics
* Nested structure analysis
* Sample data

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Analyze file
analysis = analyze_json("data.json", max_depth=5)

# Analyze data structure
data = {
    "users": [
        {"name": "Alice", "scores": [95, 87, 92]},
        {"name": "Bob", "scores": [88, 85, 90]}
    ]
}
analysis = analyze_json(data)
```

### transform\_json(data: Union\[Dict\[str, Any], str], transformations: List\[Dict\[str, Any]])

Transforms JSON data:

* Multiple operations
* Path-based modifications
* Nested transformations
* Operation types: set, delete, rename, move

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Transform data
transformations = [
    {
        "operation": "set",
        "path": "user.settings.theme",
        "value": "dark"
    },
    {
        "operation": "move",
        "path": "old.config",
        "value": "new.config"
    },
    {
        "operation": "delete",
        "path": "temporary.data"
    }
]

# Transform file
result = transform_json("config.json", transformations)

# Transform data directly
data = {"user": {"name": "Alice"}}
result = transform_json(data, transformations)
# Returns: Dict[str, Any] (transformed data)
```

## Example Agent Configuration

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent
from praisonai_tools import (
    read_json, write_json, merge_json,
    validate_json, analyze_json, transform_json
)

agent = Agent(
    name="JSONProcessor",
    description="An agent that processes JSON data",
    tools=[
        read_json, write_json, merge_json,
        validate_json, analyze_json, transform_json
    ]
)
```

## Dependencies

The JSON tools require the following Python packages:

* jsonschema: For JSON schema validation

These will be automatically installed when needed.

## Error Handling

All functions include comprehensive error handling:

* File I/O errors
* JSON parsing errors
* Schema validation errors
* Transformation errors

Errors are handled consistently:

* File operations return bool for success/failure
* Data operations return error details in result
* All errors are logged for debugging

## Common Use Cases

1. Configuration Management:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai_tools import merge_json, validate_json

# Merge multiple config files
success = merge_json(
    ["base_config.json", "env_config.json", "user_config.json"],
    "final_config.json",
    merge_arrays=True,
    overwrite_duplicates=True
)

# Validate configuration
schema = {
    "type": "object",
    "required": ["database", "api"],
    "properties": {
        "database": {
            "type": "object",
            "required": ["host", "port"]
        },
        "api": {
            "type": "object",
            "required": ["key"]
        }
    }
}
is_valid, error = validate_json("final_config.json", schema)
```

2. Data Analysis:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai_tools import analyze_json

# Analyze data structure
analysis = analyze_json("large_dataset.json", max_depth=3)
print(f"Dataset size: {analysis['structure']['size']} entries")
print(f"Available fields: {analysis['structure']['keys']}")
```

3. Data Transformation:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai_tools import transform_json, write_json

# Transform data format
transformations = [
    {"operation": "rename", "path": "firstName", "value": "first_name"},
    {"operation": "rename", "path": "lastName", "value": "last_name"},
    {"operation": "move", "path": "address.zip", "value": "address.postal_code"},
    {"operation": "delete", "path": "temporary_data"}
]
result = transform_json("user_data.json", transformations)
write_json(result, "transformed_data.json")
```

## Examples

### Basic JSON Processing Agent

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, Task, AgentTeam
from praisonai_tools import read_json, write_json, validate_json

# Create JSON processing agent
json_agent = Agent(
    name="JSONExpert",
    role="JSON Processor",
    goal="Process and validate JSON data efficiently.",
    backstory="Expert in JSON processing and validation.",
    tools=[read_json, write_json, validate_json],
    reflection=False
)

# Define JSON task
json_task = Task(
    description="Process and validate configuration files.",
    expected_output="Validated JSON configuration.",
    agent=json_agent,
    name="config_validation"
)

# Run agent
agents = AgentTeam(
    agents=[json_agent],
    tasks=[json_task],
    process="sequential"
)
agents.start()
```

### Advanced JSON Operations with Multiple Agents

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, Task, AgentTeam
from praisonai_tools import validate_json, analyze_json, transform_json, merge_json

# Create JSON validation agent
validation_agent = Agent(
    name="Validator",
    role="JSON Validation Specialist",
    goal="Ensure JSON data integrity and schema compliance.",
    tools=[validate_json, analyze_json],
    reflection=False
)

# Create JSON transformation agent
transform_agent = Agent(
    name="Transformer",
    role="JSON Transformation Specialist",
    goal="Transform and merge JSON data structures.",
    tools=[transform_json, merge_json],
    reflection=False
)

# Define tasks
validation_task = Task(
    description="Validate JSON data",
    agent=validation_agent,
    name="json_validation"
)   

transform_task = Task(
    description="Transform JSON data",
    agent=transform_agent,
    name="json_transformation"
)   

# Run agents
agents = AgentTeam(
    agents=[validation_agent, transform_agent],
    tasks=[validation_task, transform_task],
    process="sequential"
)
agents.start()
```

## Best Practices

<AccordionGroup>
  <Accordion title="Agent Configuration">
    Configure agents with clear JSON focus:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai_tools import read_json, write_json, merge_json, validate_json, analyze_json, transform_json

    Agent(
        name="JSONProcessor",
        role="JSON Processing Specialist",
        goal="Process JSON files accurately and safely",
        tools=[read_json, write_json, merge_json, validate_json, analyze_json, transform_json]
    )
    ```
  </Accordion>

  <Accordion title="Task Definition">
    Define specific JSON operations:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    Task(
        description="Parse and validate API response data",
        expected_output="Validated data structure"
    )
    ```
  </Accordion>
</AccordionGroup>

## Common Patterns

### JSON Processing Pipeline

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, Task, AgentTeam
from praisonai_tools import read_json, write_json, merge_json, validate_json, analyze_json, transform_json

# Processing agent
processor = Agent(
    name="Processor",
    role="JSON Processor",
    tools=[read_json, write_json, merge_json, validate_json, analyze_json, transform_json]
)

# Validation agent
validator = Agent(
    name="Validator",
    role="Data Validator"
)

# Define tasks
process_task = Task(
    description="Process JSON files",
    agent=processor
)

validate_task = Task(
    description="Validate processed data",
    agent=validator
)

# Run workflow
agents = AgentTeam(
    agents=[processor, validator],
    tasks=[process_task, validate_task]
)
```

## Related

<CardGroup cols={2}>
  <Card title="Custom Tools" icon="wrench" href="/docs/tools/custom">
    Build your own agent tools
  </Card>

  <Card title="Tools Overview" icon="toolbox" href="/docs/tools/tools">
    Browse PraisonAI tool documentation
  </Card>
</CardGroup>
