JSON Formatting & Parsing Code Examples
Copy-paste JSON formatting, parsing, validation, and manipulation examples for JavaScript, Python, PHP, Go, Java, and more.
Pretty-Print JSON in JavaScript
javascriptFormat JSON with indentation using JSON.stringify().
const data = { name: "Alice", age: 30, roles: ["admin", "user"] };
// Pretty-print with 2-space indent
const pretty = JSON.stringify(data, null, 2);
console.log(pretty);
// {
// "name": "Alice",
// "age": 30,
// "roles": [
// "admin",
// "user"
// ]
// }
// With tab indentation
const tabbed = JSON.stringify(data, null, '\t');
Minify JSON in JavaScript
javascriptRemove all whitespace from JSON to minimize size.
const pretty = `{
"name": "Alice",
"age": 30,
"roles": ["admin", "user"]
}`;
// Parse and re-stringify without spaces
const minified = JSON.stringify(JSON.parse(pretty));
console.log(minified);
// {"name":"Alice","age":30,"roles":["admin","user"]}
// Calculate size savings
const saved = pretty.length - minified.length;
console.log(`Saved ${saved} bytes (${Math.round(saved/pretty.length*100)}%)`);
Validate JSON in JavaScript
javascriptCheck if a string is valid JSON with a try-catch pattern.
function isValidJSON(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
}
console.log(isValidJSON('{"name": "Alice"}')); // true
console.log(isValidJSON('{name: "Alice"}')); // false
console.log(isValidJSON('')); // false
// With error message
function validateJSON(str) {
try {
return { valid: true, data: JSON.parse(str) };
} catch (e) {
return { valid: false, error: e.message };
}
}
Extract Nested JSON Fields in JavaScript
javascriptSafely access deeply nested JSON properties.
const data = {
user: {
profile: {
address: { city: "New York", zip: "10001" }
}
}
};
// Optional chaining (modern JS)
const city = data?.user?.profile?.address?.city;
console.log(city); // "New York"
const missing = data?.user?.settings?.theme;
console.log(missing); // undefined
// With default value
const theme = data?.user?.settings?.theme ?? 'light';
console.log(theme); // "light"
Pretty-Print JSON in Python
pythonFormat JSON with proper indentation using the json module.
import json
data = {"name": "Alice", "age": 30, "roles": ["admin", "user"]}
# Pretty-print with 2-space indent
pretty = json.dumps(data, indent=2)
print(pretty)
# Sort keys alphabetically
sorted_json = json.dumps(data, indent=2, sort_keys=True)
print(sorted_json)
# Ensure non-ASCII characters are preserved
data_unicode = {"name": "Аліса", "city": "Київ"}
print(json.dumps(data_unicode, indent=2, ensure_ascii=False))
Validate JSON in Python
pythonCheck if a string contains valid JSON and get error details.
import json
def validate_json(text):
try:
data = json.loads(text)
return True, data
except json.JSONDecodeError as e:
return False, f"Error at line {e.lineno}, col {e.colno}: {e.msg}"
valid, result = validate_json('{"name": "Alice"}')
print(valid, result) # True {'name': 'Alice'}
valid, result = validate_json('{name: "Alice"}')
print(valid, result) # False Error at line 1, col 2: ...
Read & Write JSON Files in Python
pythonLoad JSON from files and save formatted JSON to files.
import json
# Read JSON from file
with open('data.json', 'r') as f:
data = json.load(f)
# Write formatted JSON to file
with open('output.json', 'w') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
# Read JSON from string
text = '{"name": "Alice", "age": 30}'
data = json.loads(text)
# Convert to string
text = json.dumps(data)
Pretty-Print JSON in PHP
phpFormat JSON with PHP's json_encode options.
<?php
$data = ['name' => 'Alice', 'age' => 30, 'roles' => ['admin', 'user']];
// Pretty-print
echo json_encode($data, JSON_PRETTY_PRINT);
// Pretty-print + Unicode + unescaped slashes
echo json_encode($data,
JSON_PRETTY_PRINT |
JSON_UNESCAPED_UNICODE |
JSON_UNESCAPED_SLASHES
);
// Validate JSON
$json = '{"name": "Alice"}';
json_decode($json);
if (json_last_error() !== JSON_ERROR_NONE) {
echo "Invalid: " . json_last_error_msg();
}
Pretty-Print JSON in Go
goFormat and parse JSON using encoding/json.
package main
import (
"encoding/json"
"fmt"
)
func main() {
data := map[string]interface{}{
"name": "Alice",
"age": 30,
"roles": []string{"admin", "user"},
}
// Pretty-print
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Println(string(pretty))
// Minify (compact)
compact, _ := json.Marshal(data)
fmt.Println(string(compact))
}
Parse JSON into Structs in Go
goUnmarshal JSON into typed Go structs.
package main
import (
"encoding/json"
"fmt"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
Roles []string `json:"roles"`
}
func main() {
jsonStr := `{"name":"Alice","age":30,"roles":["admin","user"]}`
var user User
err := json.Unmarshal([]byte(jsonStr), &user)
if err != nil {
panic(err)
}
fmt.Printf("Name: %s, Age: %d\n", user.Name, user.Age)
}
Pretty-Print JSON in Java
javaFormat JSON using Jackson or Gson library.
// Using Jackson
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String json = "{\"name\":\"Alice\",\"age\":30}";
Object obj = mapper.readValue(json, Object.class);
String pretty = mapper.writeValueAsString(obj);
System.out.println(pretty);
// Using Gson
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String formatted = gson.toJson(gson.fromJson(json, Object.class));
Parse JSON in Rust
rustUse serde_json for JSON parsing and serialization.
// Cargo.toml: serde = { version = "1", features = ["derive"] }
// serde_json = "1"
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct User {
name: String,
age: u32,
roles: Vec<String>,
}
fn main() {
let json = r#"{"name":"Alice","age":30,"roles":["admin"]}"#;
// Parse into struct
let user: User = serde_json::from_str(json).unwrap();
println!("{:?}", user);
// Pretty-print
let pretty = serde_json::to_string_pretty(&user).unwrap();
println!("{}", pretty);
}
Format & Query JSON with jq (CLI)
bashUse jq command-line tool for JSON formatting and querying.
# Pretty-print JSON
echo '{"name":"Alice","age":30}' | jq .
# Minify (compact)
echo '{ "name": "Alice" }' | jq -c .
# Extract a field
echo '{"user":{"name":"Alice"}}' | jq '.user.name'
# Output: "Alice"
# Extract without quotes
echo '{"user":{"name":"Alice"}}' | jq -r '.user.name'
# Output: Alice
# Filter array elements
echo '[{"name":"Alice","age":30},{"name":"Bob","age":25}]' | \
jq '.[] | select(.age > 27)'
# Format a JSON file in-place
jq . input.json > tmp.json && mv tmp.json input.json
Pretty-Print JSON in C#
csharpFormat JSON using System.Text.Json (.NET 6+).
using System.Text.Json;
string json = "{\"name\":\"Alice\",\"age\":30}";
// Pretty-print
var options = new JsonSerializerOptions { WriteIndented = true };
var doc = JsonDocument.Parse(json);
string pretty = JsonSerializer.Serialize(doc, options);
Console.WriteLine(pretty);
// Parse and access fields
using var element = JsonDocument.Parse(json);
string name = element.RootElement.GetProperty("name").GetString();
int age = element.RootElement.GetProperty("age").GetInt32();
Pretty-Print JSON in Ruby
rubyFormat and parse JSON using Ruby's built-in JSON module.
require 'json'
data = { name: 'Alice', age: 30, roles: %w[admin user] }
# Pretty-print
puts JSON.pretty_generate(data)
# Parse JSON string
json_str = '{"name":"Alice","age":30}'
parsed = JSON.parse(json_str)
puts parsed['name'] # "Alice"
# Minify
puts JSON.generate(parsed)
# Read from file
data = JSON.parse(File.read('data.json'))
Need to work with json format, parse & validate right now?
Use our free online json formatter — no signup, no install, works in your browser.
Open JSON Formatter →