JSON Formatter — Developer Code Samples
Format JSON data programmatically using built-in language features. All examples produce the same output as the online JSON Formatter tool. No external dependencies required — Python's json module and JavaScript's JSON object handle everything.
Try the interactive version online:
Open JSON Formatter Tool →
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| json_string | str | Yes | Raw JSON string to format or parse |
| indent | int | No | Number of spaces for indentation (default: 2) |
| sort_keys | bool | No | Sort object keys alphabetically |
Returns: Formatted JSON string with proper indentation, or minified single-line JSON
Code Examples
import json
# Format (pretty-print) JSON
data = '{"name":"Alice","age":30,"city":"NYC"}'
parsed = json.loads(data)
formatted = json.dumps(parsed, indent=2, sort_keys=True)
print(formatted)
# Output:
# {
# "age": 30,
# "city": "NYC",
# "name": "Alice"
# }
# Minify JSON
minified = json.dumps(parsed, separators=(',', ':'))
print(minified)
# Output: {"age":30,"city":"NYC","name":"Alice"}
# Validate JSON
def is_valid_json(s):
try:
json.loads(s)
return True
except json.JSONDecodeError:
return False
# Format a JSON file
def format_json_file(input_path, output_path, indent=2):
with open(input_path) as f:
data = json.load(f)
with open(output_path, 'w') as f:
json.dump(data, f, indent=indent, sort_keys=True)
print(f"Formatted JSON written to {output_path}")