JSON Flatten

Flatten deeply nested JSON objects and arrays into single-level dot-notation key-value pairs instantly.

How to Flatten JSON Objects Online

1

Paste Nested JSON

Paste any nested JSON object or array payload on the left, click Upload, or click Sample.

2

Configure Delimiter

Select a preset delimiter (., _, /, -) or type a custom key separator.

3

Export Flat JSON

Flattens instantly in real time. Click Copy or Download to export single-level JSON.

Tool Options

Key Delimiter Selection

Customize key path join delimiter character (e.g. . for user.address.city or _ for user_address_city).

Recursive Object Normalization

Recursively flattens arbitrarily deep object branches and array indices into predictable single-level key-value maps.

Database & CSV Export Preparation

Prepares complex JSON documents for relational database insertion, key-value stores, or CSV tabular exports.

Your Data Privacy

Web Tool
Privacy-First Architecture
Most of our web tools process your data entirely in-browser. Where server processing is technically required, payloads are evaluated statelessly in-memory and are never stored, saved, or logged.
REST API
Stateless In-Memory Processing
When you use our API endpoints, your requests are processed strictly in-memory without persistent database storage, disk logging, or data retention.
Want to learn more about how we safeguard your information and infrastructure?
Read our full Privacy Policy for detailed security standards, data retention principles, and compliance guarantees.

What does the JSON Flatten Tool do?

The JSON Flatten Tool converts complex, deeply nested JSON objects and arrays into flat, single-level dot-notation key-value pairs in real time. Executing 100% in-browser on blueutils.com, it collapses nested object hierarchies (user.contact.email) and numerical array indices (roles.0) into uniform key paths using custom delimiters (., _, /, or -).

  • Real-Time Zero-Latency Parsing: Flattens nested JSON as you type, providing live key count metrics (X Keys).
  • Configurable Delimiters: Customize key path separators (e.g. Dot ., Underscore _, Slash /, or Hyphen -).
  • Preserves Native Values: Preserves primitive types (string, number, boolean, null), empty objects ({}), and empty arrays ([]).

Core Concepts & Technical Specifications

  1. Path Construction & Traversal:
    • Object Branches: Traverses nested keys recursively, joining parent and child keys with the chosen delimiter (user.profile.name).
    • Array Indices: Appends zero-based array indices into path strings (permissions.0.read).
    • Boundary Nodes: Primitive values, null, empty objects ({}), and empty arrays ([]) terminate path traversal and form the final leaf values.
  2. Reverse Compatibility:
    • Flattened JSON structures can be restored into their original nested hierarchy at any time using JSON Expand Tool.
  3. In-Browser Privacy:
    • All recursive traversal algorithms execute locally in browser memory.
    • Proprietary datasets and production payloads are never transmitted to external servers.

How to use the tool?

  1. Input Nested JSON:
    • Paste a nested JSON object or array into the left editor, click Upload to load a local file, or click Sample to load a pre-configured payload.
  2. Configure Delimiter:
    • Select a delimiter preset (Dot ., Underscore _, Slash /, Hyphen -) or enter a custom character in the top toolbar.
  3. Copy or Download:
    • Flattened single-level JSON appears instantly on the right. Click Copy to copy to your clipboard or Download to save as output.json.

Pipeline & Contextual Workflows

  • Tabular Data Preparation: Flatten nested documents from NoSQL databases (MongoDB, Firestore) before exporting to JSON to CSV Converter or relational SQL tables.
  • Hierarchical Reversal: Reconstruct single-level key paths back into nested JSON objects using JSON Expand Tool.
  • TypeScript Generation: Generate typed interfaces from JSON objects using JSON to TypeScript Converter.

REST API Integration

blueutils.com provides a free REST API endpoint (POST https://blueutils.com/api/json/flatten) for automated ETL pipelines, analytics preprocessing, and CI/CD data ingestion.

API Request Parameters

Name Type Description Example
rawText / json String / Object Nested JSON object, array, or string payload to flatten. "{\"user\":{\"id\":101,\"name\":\"Jane\"}}"
delimiter String Optional key path delimiter (defaults to "."). "."

API Request Payload Examples

cURL (Using Direct JSON Object)

curl -X POST https://blueutils.com/api/json/flatten \
  -H "Content-Type: application/json" \
  -d '{
    "json": {
      "user": {
        "id": 101,
        "contact": {
          "email": "jane@example.com"
        }
      }
    },
    "delimiter": "."
  }'

cURL (Using Raw String & Underscore Delimiter)

curl -X POST https://blueutils.com/api/json/flatten \
  -H "Content-Type: application/json" \
  -d '{
    "rawText": "{\"user\":{\"id\":101,\"name\":\"Jane\"}}",
    "delimiter": "_"
  }'

Python

import requests

url = "https://blueutils.com/api/json/flatten"
payload = {
    "json": {
        "user": {
            "id": 101,
            "name": "Jane"
        }
    },
    "delimiter": "."
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.json())

Java

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String jsonPayload = """
            {
                "rawText": "{\\"user\\":{\\"id\\":101,\\"name\\":\\"Jane\\"}}",
                "delimiter": "."
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://blueutils.com/api/json/flatten"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
            .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

API Response Parameters

Name Type Description Example
isValid Boolean Returns true if the flatten operation succeeded. true
result String Transformed single-level dot-notation JSON string. "{\n \"user.id\": 101,\n \"user.name\": \"Jane\"\n}"
data Object Parsed flattened single-level JavaScript object. {"user.id":101,"user.name":"Jane"}
originalSize Number Byte size of raw input JSON in UTF-8. 45
resultSize Number Byte size of flattened output JSON in UTF-8. 54
keyCount Number Total count of flattened single-level keys. 2
error String Detailed error explanation returned on invalid syntax. "Invalid JSON syntax: Unexpected token '}' (Line 2)"

API Response Payload Examples

Success Response (HTTP 200 OK)

{
  "isValid": true,
  "result": "{\n  \"user.id\": 101,\n  \"user.name\": \"Jane Doe\"\n}",
  "data": {
    "user.id": 101,
    "user.name": "Jane Doe"
  },
  "originalSize": 45,
  "resultSize": 54,
  "keyCount": 2
}

Validation Failure Response (HTTP 400 Bad Request)

{
  "isValid": false,
  "error": "Invalid JSON syntax: Unexpected token '}' at position 15 (Line 1, Column 16)"
}

Rate Limit Exceeded Response (HTTP 429 Too Many Requests)

{
  "error": "API rate limit exceeded. Please wait or contact support@blueutils.com."
}

Why use an API to flatten JSON?

Automating JSON flattening simplifies multi-system data processing:

  • Relational Ingestion: Flattens nested document stores (MongoDB, Firestore) into flat schemas compatible with PostgreSQL, Snowflake, and BigQuery.
  • LLM Context Minimization: AI agents often need to reference specific deeply nested values. Flattened keys allow direct access without navigating deep object graphs.
  • Deterministic Key Traversal: Guarantees deterministic path ordering and separator joining across batch jobs.

Native Usage

Flatten nested JSON locally across terminal environments and programming runtimes:

Linux / macOS (jq)

# Flatten JSON using jq in terminal
jq -r '[paths(scalars) as $p | { ($p | join(".")): getpath($p) }] | add' input.json

Windows (PowerShell)

# Flatten JSON using Node.js in PowerShell
node -e "function f(o,p=''){let r={};for(let k in o){let n=p?p+'.'+k:k;if(typeof o[k]==='object'&&o[k]!==null)Object.assign(r,f(o[k],n));else r[n]=o[k];}return r;} console.log(f({user:{id:101,name:'Jane'}}));"

Python

import json

def flatten_json(data, delimiter="."):
    out = {}
    def flatten(obj, name=""):
        if isinstance(obj, dict):
            for k, v in obj.items():
                flatten(v, f"{name}{k}{delimiter}" if name else f"{k}{delimiter}")
        elif isinstance(obj, list):
            for i, v in enumerate(obj):
                flatten(v, f"{name}{i}{delimiter}" if name else f"{i}{delimiter}")
        else:
            out[name[:-len(delimiter)]] = obj
    flatten(data)
    return out

sample = {"user": {"id": 101, "name": "Jane Doe"}}
print(json.dumps(flatten_json(sample), indent=2))

Java (Jackson)

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void flatten(String prefix, JsonNode node, Map<String, Object> out) {
        if (node.isObject()) {
            node.fields().forEachRemaining(entry -> 
                flatten(prefix.isEmpty() ? entry.getKey() : prefix + "." + entry.getKey(), entry.getValue(), out)
            );
        } else {
            out.put(prefix, node.asText());
        }
    }

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree("{\"user\":{\"name\":\"Jane Doe\"}}");
        Map<String, Object> flat = new LinkedHashMap<>();
        flatten("", root, flat);
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(flat));
    }
}

Frequently Asked Questions (FAQ)

What is JSON flattening?

JSON flattening is the process of converting a deeply nested JSON object or array structure into a single-level object where keys are joined by a delimiter (like dot-notation user.address.city).

Why should I flatten JSON objects?

Flattening JSON simplifies inserting complex payloads into relational SQL databases, exporting data to tabular CSV spreadsheets, or indexing documents in key-value stores.

How are nested arrays handled during flattening?

Arrays are flattened by appending numerical indices to their parent key path (for example, roles.0, roles.1, items.0.id).

Can I choose a custom delimiter instead of dots?

Yes. You can select common presets (such as _, /, -) or enter any custom delimiter character in the Delimiter input.

Is my nested JSON payload stored or sent to remote servers?

No. All object flattening is executed 100% in-browser client-side. Your private JSON payloads never leave your machine.

Rate Limits

UI Limits
100 uses per 15 minutes
Max payload size: 5 MB
API Limits
5 requests per 60 minutes
Max payload size: 256 KB
Need higher API rate limits, increased payload sizes, or custom developer solutions?
Contact our engineering team at support@blueutils.com for custom rate limit increases, higher quota allocations, or tailored enterprise integrations.