JSON Agent

JSON data processing tools for AI agents.

python
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.

Diagram

Input

Agent

Tool

Output

Diagram
JSON AgentAgentUserJSON AgentAgentUserRequestProcess requestResultResponse

JSON Tools

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

  1. Install Dependencies

    First, install the required packages:

    bash
    pip install praisonaiagents praisonai-tools
  2. Import Components

    Import the necessary components:

    python
    from praisonaiagents import Agent, Task, AgentTeam
    from praisonai_tools import (
        read_json, write_json, merge_json,
        validate_json, analyze_json, transform_json
    )
  3. Create Agent

    Create a JSON processing agent:

    python
    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
    )
  4. Define Task

    Define the JSON processing task:

    python
    json_task = Task(
        description="Parse and validate API response data.",
        expected_output="Validated and processed JSON data.",
        agent=json_agent,
        name="json_processing"
    )
  5. Run Agent

    Initialize and run the agent:

    python
    agents = AgentTeam(
        agents=[json_agent],
        tasks=[json_task],
        process="sequential"
    )
    agents.start()

Understanding JSON Tools

What are JSON Tools?

JSON Tools provide JSON processing capabilities for AI agents: – File reading and writing – Data validation – Schema validation – Data transformation – Structure analysis

Key Components

Available Functions

python
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
# 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
# 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
# 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
# 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
# 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
# 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
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
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)
  1. Data Analysis:
python
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']}")
  1. Data Transformation:
python
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
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
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

Agent Configuration

Configure agents with clear JSON focus:

python
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]
)
Task Definition

Define specific JSON operations:

python
Task(
    description="Parse and validate API response data",
    expected_output="Validated data structure"
)

Common Patterns

JSON Processing Pipeline

python
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