JSON formatter and validator
An API returns {"sku":"A17","qty":2}. A person can read that order line at a glance. A response with hundreds of lines like it is easier to inspect when you can see where each item begins and ends. Use the JSON formatter to make the structure visible or find the character that stops a parser.
Loading the tool…
What is JSON, and where is it used?
JSON (JavaScript Object Notation) is a text format for exchanging structured data. In the order line above, an object groups two named properties: sku holds a string and qty holds a number. An order with several lines can put those objects in an array:
{"items":[{"sku":"A17","qty":2},{"sku":"B08","qty":1}]}
Array positions start at zero. To find the quantity of the second item, follow items, index 1, then qty. The JSON Pointer for that value is /items/1/qty. Look up an object’s properties by name, since their order can change between producers.
JSON also supports booleans (true and false) and null. A missing property and a property explicitly set to null can mean different things to an API. Dates have no built-in JSON type, so systems exchanging a delivery date need to agree on a representation, such as the string "2026-12-01".
A JavaScript storefront can submit an order as UTF-8 JSON with the HTTP content type application/json, and a Python service can read it. The same format works for a configuration file or a saved test response. For an HTTP request, the receiving endpoint determines which body formats it accepts. Compare JSON, form data, and multipart requests or build a cURL request.
What does JSON validation check?
| Question | Example | How to check |
|---|---|---|
| Can a parser read the text? | {"qty":2,} has a comma with no property after it. | A syntax validator reads one complete JSON value and reports where the grammar breaks. |
| Does the data have the expected shape? | {"sku":"A17","qty":"2"} parses, but the quantity is a string. | A schema validator checks required properties, types, and constraints such as a minimum quantity. |
| Can this order be fulfilled? | A quantity of 2 meets the schema, but only one unit is in stock. | The application checks the order against current inventory. |
The validator above checks syntax. Property names and strings need double quotes. Comments and trailing commas are syntax errors. If the reported location is the start of the next property, look just before it for a missing comma. A document contains one top-level value, which can also be a string, number, boolean, or null.
Repeated keys deserve separate attention. The text {"qty":2,"qty":5} satisfies the JSON grammar, yet parsers can disagree about which quantity survives. The formatter preserves both entries and warns about the repeat. Resolve the ambiguity in the source before relying on a parsed value.
For the order line, this JSON Schema gives the receiving application a reusable rule. Pass both this schema and the parsed order line to a JSON Schema validator. The number 2 passes, the string "2" fails the type check, and 0 fails the minimum.
{
"type": "object",
"required": ["sku", "qty"],
"properties": {
"sku": { "type": "string" },
"qty": { "type": "integer", "minimum": 1 }
}
}
The same distinction matters when an AI produces a response that looks plausible. See a worked example of checking the fields an application actually needs.
What changes when you format or minify JSON?
A pretty-printer inserts line breaks and indentation between tokens. The compact order line at the top of this page becomes:
{
"sku": "A17",
"qty": 2
}
One property per line makes a change from two units to five easy to spot in a code review. Minification removes optional whitespace for a smaller file or request body. Both operations must preserve spaces inside a string: "dark blue" and "darkblue" are different values. Removing whitespace with a blanket text replacement can change the order itself.
Formatting source text and serializing a parsed object can produce different results. For example, converting 9007199254740993 to a JavaScript Number rounds it to 9007199254740992; serializing the value cannot recover the digit. A serializer may also write 12.5 where the source said 12.50. This formatter changes whitespace between tokens and keeps the original digits, escapes, key order, and repeated keys. When checking a signature over the original bytes, use the original document: even a line break changes those bytes.
JSON vs. CSV, YAML, and XML: which fits the data?
| Format | Choose it when | A trade-off to consider |
|---|---|---|
| JSON | An API returns an order with a customer, a list of items, and optional delivery details. | Objects and arrays express nesting directly. People maintaining a JSON configuration cannot add comments in standard JSON. |
| CSV | A colleague wants one order line per spreadsheet row. | Rows and columns suit a flat export. Agree on column types and how to represent missing values and leading zeros. |
| YAML | People edit a configuration by hand and need comments explaining their choices. | Indentation carries structure. Check that the target application supports the YAML features you use. |
| XML | A document mixes running text with marked-up phrases, or a partner requires XML namespaces and a published schema. | Elements and attributes can express these distinctions; converting to JSON requires deciding how to preserve them. |
How to parse and pretty-print JSON in code
Each example reads the same order line and writes indented JSON. Most parse the input into a language value and serialize it again. Go shows how to indent the source directly. These are syntax and formatting examples; checking the order’s required fields is a separate step.
JavaScript / TypeScript
Browsers and Node.js provide both methods. TypeScript uses the same runtime parser; a type annotation alone cannot check incoming text. MDN JSON.parse reference.
const source = '{"sku":"A17","qty":2}';
const item = JSON.parse(source); // Throws SyntaxError for malformed JSON.
console.log(JSON.stringify(item, null, 2));
Python
Python’s decoder accepts NaN and infinity by default. The callback below rejects those extensions, and the encoder also checks for non-finite output. Python json module.
import json
def reject_constant(token):
raise ValueError(token) # NaN and Infinity are outside the JSON grammar.
item = json.loads('{"sku":"A17","qty":2}', parse_constant=reject_constant)
print(json.dumps(item, indent=2, ensure_ascii=False, allow_nan=False))
PHP
Keep JSON objects as objects when decoding. Turning an empty object into an associative PHP array can make it come back as an empty JSON array. This example uses PHP 7.3 or later. PHP json_decode reference.
<?php
$source = '{"sku":"A17","qty":2}';
// A decoding error throws; a JSON null is still a valid result.
$item = json_decode($source, false, 512, JSON_THROW_ON_ERROR);
echo json_encode($item, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR), PHP_EOL;
C# / .NET
Use a read-only JsonDocument to format a payload whose fields you do not need to model as a C# class. Microsoft guide to the System.Text.Json document model.
using System;
using System.Text.Json;
using var doc = JsonDocument.Parse("{\"sku\":\"A17\",\"qty\":2}");
// Serialize the root value to keep its JSON structure.
var options = new JsonSerializerOptions { WriteIndented = true };
Console.WriteLine(JsonSerializer.Serialize(doc.RootElement, options));
Go
Indent writes directly from the source bytes. It can lay out an object without converting its numbers to float64. Compact performs the reverse whitespace operation. Go encoding/json reference.
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
)
func main() {
src := []byte(`{"sku":"A17","qty":2}`)
var out bytes.Buffer
if err := json.Indent(&out, src, "", " "); err != nil {
log.Fatal(err) // Report malformed input before printing the buffer.
}
fmt.Println(out.String())
}
Rust
Add serde_json to the project with cargo add serde_json. Use Value when the document structure can vary. serde_json crate documentation.
use serde_json::Value;
fn main() -> serde_json::Result<()> {
let src = r#"{"sku":"A17","qty":2}"#;
let item: Value = serde_json::from_str(src)?; // Return a parsing error to the caller.
println!("{}", serde_json::to_string_pretty(&item)?);
Ok(())
}
Java
This example uses Jackson 2.x (com.fasterxml.jackson.core:jackson-databind). Enable the trailing-token check when a file must contain exactly one value. Jackson 2 databind documentation.
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
class OrderLine {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
// Reject a second value after the order line.
mapper.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
JsonNode item = mapper.readValue("{\"sku\":\"A17\",\"qty\":2}", JsonNode.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(item));
}
}
Swift
Foundation reads and writes Data. Allow fragments on both calls if the root can also be a string, number, boolean, or null. Apple JSONSerialization reference.
import Foundation
let source = Data(#"{"sku":"A17","qty":2}"#.utf8)
let item = try JSONSerialization.jsonObject(with: source, options: [.fragmentsAllowed])
// Request indentation when writing the UTF-8 result.
let pretty = try JSONSerialization.data(withJSONObject: item, options: [.prettyPrinted, .fragmentsAllowed])
print(String(decoding: pretty, as: UTF8.self))
Delphi / Object Pascal
Delphi’s System.JSON unit returns a TJSONValue that the caller owns. Format takes the indentation width. RAD Studio Format reference.
program OrderLine;
{$APPTYPE CONSOLE}
uses System.SysUtils, System.JSON;
var
Item: TJSONValue;
begin
Item := TJSONValue.ParseJSONValue('{"sku":"A17","qty":2}');
if Item = nil then
raise EConvertError.Create('Invalid JSON');
try
Writeln(Item.Format(2));
finally
Item.Free; // Release the parsed tree even if writing fails.
end;
end.
How to use this tool
- Paste into JSON source, open a local UTF-8 file with the folder button, or choose Try an example. The source stays editable as you inspect the result.
- Choose two spaces, four spaces, tabs, or one-line output. Syntax checks run as you type. Select a reported location to return to the source.
- Open Explore keys and values to filter the current level, select an entry, copy a value or its JSON Pointer, and move up again. Array indexes start at zero. To jump directly to a known value, enter its pointer and press Enter. An empty pointer returns to the root.
- Use the copy or download button beside JSON result for the whole document. Download saves the selected formatting in a UTF-8
.jsonfile.
The tool accepts up to 1 million UTF-16 units of source, 2 MB per local file, 100,000 values and 128 nested containers. If indentation would exceed 4 million UTF-16 units, use one-line output or copy a value from the explorer.
Your tool data stays in your browser
This tool processes your data on your device. The text, files, or passwords you enter and the results it creates are not sent to our servers or any other server.
Page and asset requests still occur. Production pages also load Google Tag Manager, Cloudflare Web Analytics, and AdSense advertising; tool code does not send inputs or results to analytics or ads. See our privacy policy.
To inspect requests while using the tool, open your browser's developer tools and select Network. Try it with sample data.
Read How to Check Website Network Requests in Chrome, Firefox, Edge and Safari.
JSON references
- The diagrams on JSON.org show where separators belong and how strings and numbers are written. Introducing JSON.
- The Internet Standard defines the grammar and explains interoperability issues with numbers and repeated names. RFC 8259.
- The JSON Schema project’s guide shows how to describe object properties and make individual fields mandatory. Understanding object schemas.