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
- 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.
- Object Branches: Traverses nested keys recursively, joining parent and child keys with the chosen delimiter (
- Reverse Compatibility:
- Flattened JSON structures can be restored into their original nested hierarchy at any time using JSON Expand Tool.
- 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?
- 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.
- Configure Delimiter:
- Select a delimiter preset (Dot
., Underscore_, Slash/, Hyphen-) or enter a custom character in the top toolbar.
- Select a delimiter preset (Dot
- 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.
- Flattened single-level JSON appears instantly on the right. Click Copy to copy to your clipboard or Download to save as
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.jsonWindows (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));
}
}