DevToolsForYou

JSON Formatter, Minifier, and Validator in Python — Code Examples

JSON Formatter, Minifier, and Validator in PythonUse the online tool →

JSON parsing and serialisation is built into every major language. Here is how to parse a JSON string, format (pretty-print) JSON, and handle common edge cases in each language.

Python's json module has json.loads() for parsing and json.dumps() for serialization. Use indent for pretty-printing.

Python 3
import json

# Parse JSON string → dict
data = json.loads('{"name": "Alice", "age": 30}')
print(data["name"])  # Alice

# Serialize dict → JSON string
json_str = json.dumps(data)
print(json_str)  # {"name": "Alice", "age": 30}

# Pretty-print
pretty = json.dumps(data, indent=2)
print(pretty)
# {
#   "name": "Alice",
#   "age": 30
# }

# Sort keys alphabetically
sorted_json = json.dumps(data, sort_keys=True, indent=2)

# Read/write JSON files
with open("data.json", "w") as f:
    json.dump(data, f, indent=2)

with open("data.json") as f:
    loaded = json.load(f)

# Custom serializer for non-JSON types (e.g. datetime)
from datetime import datetime

class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        return super().default(obj)

print(json.dumps({"ts": datetime.now()}, cls=DateEncoder))
Notes & gotchas
  • json.loads() raises json.JSONDecodeError on invalid JSON (a subclass of ValueError).
  • Python dicts are ordered (Python 3.7+) — json.dumps() preserves insertion order.
  • Use ensure_ascii=False in json.dumps() to output Unicode characters directly instead of \uXXXX escapes.
Try it in your browser

Need to json formatter without writing code? The JSON Formatter, Minifier, and Validator runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open JSON Formatter
JSON Formatter, Minifier, and Validator in other languages