Free Online JSON to TOON Converter

This tool converts JSON to TOON format, a compact text format that uses fewer tokens when sent to language models. TOON removes JSON's curly braces and repeated keys, cutting token usage by 30-60%. Runs in your browser, free.

JSON to TOON

Want to test drive the tool?

Before & After

Standard JSON Format
json
{
  "users": [
    {"id": 1, "name": "John Doe", "email": "john@example.com", "active": true, "department": "Engineering", "salary": 75000},
    {"id": 2, "name": "Jane Smith", "email": "jane@example.com", "active": false, "department": "Marketing", "salary": 65000},
    {"id": 3, "name": "Bob Johnson", "email": "bob@example.com", "active": true, "department": "Engineering", "salary": 80000}
  ],
  "metadata": {"version": "1.0", "created": "2024-01-01"}
}
Optimized TOON Format
json
users:
id,name,email,active,department,salary
1,John Doe,john@example.com,true,Engineering,75000
2,Jane Smith,jane@example.com,false,Marketing,65000
3,Bob Johnson,bob@example.com,true,Engineering,80000

metadata:
version,1.0
created,2024-01-01

TOON vs JSON Comparison

Detailed comparison between JSON and TOON serialization formats
FeatureStandard JSONTOON FormatAdvantage
Token EfficiencyBaseline (100%)30-60% reductionTOON saves tokens
Human ReadabilityGood for developersExcellent for bothTOON maintains clarity
LLM ProcessingVerbose syntaxOptimized structureTOON reduces complexity
API Cost ImpactFull pricing30-60% savingsTOON cuts costs
Data Integrity100% preserved100% preservedEqual reliability
Array HandlingRepetitive structureTabular optimizationTOON eliminates redundancy
Nested ObjectsDeep nestingKey folding optionTOON flattens efficiently
File SizeLarge payloadsCompact representationTOON reduces bandwidth
Processing SpeedStandard parsingFaster LLM processingTOON improves performance
ReversibilityNot applicableLossless conversionTOON maintains compatibility

Frequently Asked Questions

Code Examples

How to Convert JSON to TOON in Python

Converting JSON to TOON format in Python involves transforming standard JSON into a token-optimized notation that reduces size for LLM APIs. Parse your JSON with json.load(), apply compression rules like removing whitespace, shortening keys, and using compact notation. Custom serializers can implement TOON-specific optimizations. Perfect for reducing API costs when sending large JSON payloads to GPT, Claude, or other language models where token count directly impacts pricing.

Pythonjson_to_toon.py
import json
import csv
from io import StringIO

def json_to_toon(json_data, delimiter=",", optimize_arrays=True):
    """
    Convert JSON to TOON format with advanced optimization
    
    Args:
        json_data: JSON string or Python object
        delimiter: Field separator (',', '|', '\t', ';')
        optimize_arrays: Enable array-to-table optimization
    
    Returns:
        Optimized TOON format string
    """
    
    if isinstance(json_data, str):
        data = json.loads(json_data)
    else:
        data = json_data
    
    def convert_array_to_table(arr):
        if not arr or not isinstance(arr[0], dict):
            return str(arr)
        
        # Get all unique keys
        keys = set()
        for item in arr:
            keys.update(item.keys())
        keys = sorted(keys)
        
        # Create CSV-like format
        output = StringIO()
        writer = csv.writer(output, delimiter=delimiter)
        writer.writerow(keys)
        
        for item in arr:
            row = [item.get(key, '') for key in keys]
            writer.writerow(row)
            
        return output.getvalue().strip()
    
    def process_object(obj, prefix=""):
        if isinstance(obj, list) and optimize_arrays:
            return convert_array_to_table(obj)
        elif isinstance(obj, dict):
            result = []
            for key, value in obj.items():
                if isinstance(value, (dict, list)):
                    nested = process_object(value, f"{prefix}{key}.")
                    result.append(f"{key}:\n{nested}")
                else:
                    result.append(f"{key}{delimiter}{value}")
            return "\n".join(result)
        else:
            return str(obj)
    
    return process_object(data)

# Example usage
json_input = '''{"users": [{"id": 1, "name": "John"}], "count": 1}'''
toon_output = json_to_toon(json_input)
print(f"Original tokens: ~{len(json_input.split())}")
print(f"TOON tokens: ~{len(toon_output.split())}")
print(f"Reduction: ~{(1 - len(toon_output.split())/len(json_input.split()))*100:.1f}%")

How to Convert JSON to TOON in JavaScript

Converting JSON to TOON in JavaScript uses custom serialization to create token-efficient representations. Implement compression strategies like abbreviating common keys, removing unnecessary whitespace, and using compact array notation. The JSON.stringify() replacer function lets you customize output format. Ideal for frontend applications sending data to AI APIs, reducing bandwidth costs, or optimizing prompts for token-limited LLM contexts in Node.js backends.

JavaScriptJsonToToonConverter.js
class JsonToToonConverter {
    constructor(options = {}) {
        this.delimiter = options.delimiter || ',';
        this.optimizeArrays = options.optimizeArrays !== false;
        this.removeNulls = options.removeNulls || false;
        this.compressStrings = options.compressStrings || false;
    }
    
    /**
     * Convert JSON to TOON format with token optimization
     * @param {string|object} jsonData - JSON input
     * @returns {string} Optimized TOON format
     */
    convert(jsonData) {
        const data = typeof jsonData === 'string' 
            ? JSON.parse(jsonData) 
            : jsonData;
            
        return this.processValue(data);
    }
    
    processValue(value, depth = 0) {
        if (value === null || value === undefined) {
            return this.removeNulls ? '' : 'null';
        }
        
        if (typeof value === 'string') {
            if (this.compressStrings && value.length > 50) {
                return '"' + value.replace(/\s+/g, ' ').trim() + '"';
            }
            return '"' + value + '"';
        }
        
        if (typeof value === 'number' || typeof value === 'boolean') {
            return String(value);
        }
        
        if (Array.isArray(value)) {
            return this.optimizeArrays && this.canOptimizeArray(value)
                ? this.arrayToTable(value)
                : '[' + value.map(item => this.processValue(item, depth + 1))
                    .join(this.delimiter) + ']';
        }
        
        if (typeof value === 'object') {
            const entries = Object.entries(value)
                .filter(([_, v]) => !this.removeNulls || (v !== null && v !== undefined));
                
            return entries.map(([key, val]) => 
                key + this.delimiter + this.processValue(val, depth + 1)
            ).join('\n');
        }
        
        return String(value);
    }
    
    canOptimizeArray(arr) {
        return arr.length > 0 && 
               typeof arr[0] === 'object' && 
               arr[0] !== null &&
               !Array.isArray(arr[0]);
    }
    
    arrayToTable(arr) {
        const keys = [...new Set(arr.flatMap(Object.keys))];
        const header = keys.join(this.delimiter);
        const rows = arr.map(item => 
            keys.map(key => item[key] ?? '').join(this.delimiter)
        );
        return header + '\n' + rows.join('\n');
    }
    
    /**
     * Calculate token reduction estimate
     * @param {string} original - Original JSON
     * @param {string} converted - TOON format
     * @returns {object} Statistics
     */
    calculateSavings(original, converted) {
        const originalTokens = this.estimateTokens(original);
        const convertedTokens = this.estimateTokens(converted);
        const reduction = ((originalTokens - convertedTokens) / originalTokens) * 100;
        const savings = ((originalTokens - convertedTokens) / 1000) * 0.03; // GPT-4 pricing
        
        return {
            originalTokens,
            convertedTokens,
            reduction: Math.max(0, reduction),
            savings: Math.max(0, savings),
            compressionRatio: originalTokens / convertedTokens
        };
    }
    
    estimateTokens(text) {
        const words = text.split(/\s+/).filter(Boolean).length;
        const punctuation = (text.match(/[.,;:!?(){}\[\]"']/g) || []).length;
        const numbers = (text.match(/\d+/g) || []).length;
        return Math.ceil((words + punctuation * 0.5 + numbers * 0.5) * 1.2);
    }
}

// Usage example
const converter = new JsonToToonConverter({
    delimiter: ',',
    optimizeArrays: true,
    removeNulls: true,
    compressStrings: true
});

const jsonData = '{"users": [{"id": 1, "name": "John"}]}';
const toonData = converter.convert(jsonData);
const stats = converter.calculateSavings(jsonData, toonData);

console.log('TOON Output:', toonData);
console.log('Token Reduction:', stats.reduction.toFixed(1) + '%');
console.log('API Savings: $' + stats.savings.toFixed(4));

Complete TOON Conversion Guide

What changes between JSON and TOON

JSON uses curly braces, quotes around keys, colons, and commas for every object. TOON removes all of that. For arrays of objects, TOON writes the keys once as a header row, then writes each object as a comma-separated line - like a CSV table. For example, JSON writes {"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"} but TOON writes id,name then 1,Alice then 2,Bob on separate lines.

For nested objects, TOON flattens the structure using dot notation. A JSON object like {"user": {"name": "Alice", "age": 30}} becomes user.name,Alice and user.age,30 in TOON. This eliminates the curly braces and nesting tokens.

The biggest token savings come from arrays. If you have 100 user objects in JSON, you repeat the keys "id", "name", "email" 100 times. TOON writes those keys once. That's where the 30-60% token reduction comes from.

TOON stays human-readable. You can open a TOON file in a text editor and understand it immediately. It looks like a simplified CSV with sections for different data types.

When you'd convert JSON to TOON

You convert JSON to TOON when you're sending data to a language model API and you're paying per token. GPT-4, Claude, and Gemini all charge based on how many tokens you send. If you're sending product catalogs, user lists, or database exports to an LLM, converting to TOON first cuts your API bill by 30-60%.

Developers building chatbots, AI assistants, or automated content generators use TOON to fit more context into the model's token limit. If GPT-4 has a 128k token limit and your JSON data uses 50k tokens, converting to TOON might get that down to 25k tokens - letting you include twice as much data in the same prompt.

TOON is specifically designed for LLM token optimization. It's not a general-purpose data format. You wouldn't use it for APIs, databases, or config files - those all expect JSON. TOON is for the specific case where you need to minimize tokens sent to a language model.

Converting back from TOON to JSON

Yes, TOON can be converted back to JSON without losing data. The conversion is lossless - you get the exact same structure and values. However, there's no widely-used TOON to JSON converter yet because TOON is primarily a one-way optimization for sending data to LLMs.

If you need to round-trip the data, you'd keep the original JSON and only convert to TOON right before sending to the language model. The typical workflow is: store data as JSON, convert to TOON when making an API call, then discard the TOON version after the LLM processes it.