How to Format JSON in Python (and Fix Common Errors)
Originally published on DevToolsHub — free, privacy-first online tools for developers.
Every Python developer formats JSON eventually — pretty-printing an API
payload for a bug report, dumping a config file so humans can read it, or
running a quick validation check before feeding data to another service.
The good news is that Python ships with everything you need in its
standard library: json.dumps() for formatting inside your
code, and the python -m json.tool one-liner for the terminal.
The bad news is that the first error message you will hit —
json.decoder.JSONDecodeError: Expecting property name enclosed in — is famously cryptic when you just want to know
double quotes
where your JSON is broken.
This guide covers both halves of the job. First, the clean ways to format and pretty-print JSON in Python, including the difference between `json.load()` and `json.loads()` and how to produce compact output for network transfer. Then a field guide to the three JSON errors you will actually encounter in practice, why they happen, and the exact fix for each one. 💡 Quick Try No Python handy? Paste any JSON into our free
JSON Formatter
to pretty-print, minify, and validate it instantly in your browser — the
same output you would get from json.dumps(data, indent=2) ,
with error line numbers when the input is broken.
Pretty-Print JSON with json.dumps
The core workflow is always the same: parse the JSON string into a Python object, then serialize it back with formatting options. The `indent` parameter controls how many spaces each nesting level gets, and `sort_keys=True` alphabetizes keys so diffs stay readable: import json data = {"name": "Ada", "languages": ["python", "sql"], "id": 42} # Pretty-print with 2-space indentation print(json.dumps(data, indent=2)) # { # "name": "Ada", # "languages": [ # "python", # "sql" # ], # "id": 42 # } # Sorted keys + indentation — great for config files in git print(json.dumps(data, indent=2, sort_keys=True)) # Write directly to a file with open("output.json", "w", encoding="utf-8") as f: json.dump(data, f, indent=2, ensure_ascii=False) Two details worth knowing. `ensure_ascii=False` keeps non-ASCII characters (emoji, accented letters, CJK text) as-is instead of escaping them into `\uXXXX` sequences — always set it when writing files that humans will read, and always open those files with `encoding="utf-8"`. And if you want trailing newlines or custom spacing between items, the `separators` parameter (covered below) gives you full control. Format JSON from the Command Line with json.tool
When you are debugging in a terminal — inspecting a curl response, checking a log file, validating a downloaded config — you do not need to write a script. Python ships a module that formats JSON straight from stdin or a file: # From a pipe — the classic curl pretty-print curl -s https://api.example.com/users/1 | python3 -m json.tool # From a file, writing formatted output elsewhere python3 -m json.tool messy.json > pretty.json # Sort keys too (Python 3.5+ supports --sort-keys) python3 -m json.tool --sort-keys config.json # Compact instead of pretty (Python 3.4+) python3 -m json.tool --compact messy.json `json.tool` doubles as a validator: if the input is invalid, it prints the parse error with line and column numbers and exits with a non-zero status, so you can drop it into shell scripts and CI checks. Note that it does not accept flags like `indent` beyond the ones shown — for full control over the output shape, use a `python -c` one-liner with `json.dumps`. json.load vs json.loads: Which One Do I Use?
The distinction trips up almost everyone at first, but it is a single letter with a simple rule. `json.loads()` parses a **string** (the trailing `s` stands for string) — this is what you use on HTTP response bodies and any JSON you have in memory. `json.load()` reads directly from a **file object** and saves you the two-step dance: import json # json.loads — parse a STRING (note the s) raw = '' data = json.loads(raw) # json.load — read from a FILE OBJECT with open("config.json", encoding="utf-8") as f: config = json.load(f) # Equivalent — this is what json.load does internally with open("config.json", encoding="utf-8") as f: config = json.loads(f.read()) # The same split exists on the write side: json.dumps(obj) # object -> string json.dump(obj, f) # object -> file Both raise `json.JSONDecodeError` (a subclass of `ValueError`) when the input is not valid JSON, so a single `except json.JSONDecodeError` block covers both call styles. Everything else follows the same rule: functions ending in `s` work with strings, the plain ones work with file handles. Compact JSON Output with separators
By default `json.dumps` inserts a space after every `,` and `:` — fine for humans, wasteful for network payloads and message queues. To get the tightest possible encoding (the format JavaScript's `JSON.stringify` produces by default), override `separators`: import json data = print(json.dumps(data)) # print(json.dumps(data, separators=(",", ":"))) # # Measure the savings on a real payload compact = json.dumps(data, separators=(",", ":")) pretty = json.dumps(data, indent=2) print(len(pretty), "vs", len(compact)) A useful habit: keep two profiles in your codebase — `indent=2, sort_keys=True` for anything a human will open, and `separators=(",", ":")` for anything the network will carry. For machine-to-machine traffic you can also drop `sort_keys`, since key order is irrelevant to JSON consumers. Fixing “Expecting property name enclosed in double quotes”
This is the most-reported JSON error in Python, and it has two usual suspects. The error means the parser expected a key wrapped in double quotes and found something else — most often a **trailing comma** or a **single-quoted key**, both of which are legal in Python dicts but illegal in JSON: import json # Culprit 1: trailing comma after the last item json.loads('') # JSONDecodeError: Expecting property name enclosed in double quotes # Fix: remove the trailing comma json.loads('') # Culprit 2: single quotes around keys or values json.loads("") # JSONDecodeError: Expecting property name enclosed in double quotes # Fix: use double quotes everywhere json.loads('') The trailing comma is the sneakiest of the two, because many editors (and every JavaScript engine since ES5) silently tolerate it in object literals, so the data *looks* fine in one context and breaks in another. If the JSON came from a JavaScript file, comment lines are a third possibility — JSON has no comments, full stop. When you control the data source, standardize on double quotes and no trailing commas, and let your editor's JSON language mode flag violations on save. Fixing “Expecting value: line 1 column 1 (char 0)”
This error means the parser reached the very first character and found nothing it could parse. In practice that is almost always one of three situations: an **empty response body** (the API returned 204 No Content or an error page), a **BOM prefix** on a Windows-authored file, or you are accidentally passing an empty variable: import json # Situation 1: empty API response — check before parsing resp_body = response.text if not resp_body.strip(): raise ValueError("Empty response body — check status code") # Situation 2: UTF-8 BOM (\ufeff) at the start of the file. # Plain utf-8 decoding leaves the BOM in place and parsing fails: with open("data.json", encoding="utf-8-sig") as f: data = json.load(f) # utf-8-sig strips the BOM automatically # Equivalent fix for a string you already have in memory data = json.loads(raw.lstrip("\\ufeff")) # Debugging aid: print the first characters with repr to see hidden bytes print(repr(raw[:20])) The `encoding="utf-8-sig"` trick is the one to remember: it behaves exactly like `utf-8` but silently removes a BOM if present, and reads ordinary UTF-8 files without any change. It costs nothing and eliminates an entire class of “it works on my machine” bugs caused by files exported from Excel or edited in Windows tools. When nothing obvious is wrong, `repr()` is your friend — it exposes hidden characters that normal printing swallows. Handling Single-Quoted JSON (Python-Style Dicts)
Data pasted from a Python session prints like a dict — `"}` — with single quotes and sometimes `True`/`None`/`False` in place of `true`/`null`/`false`. That is not JSON, and `json.loads` will reject it. If you cannot get a proper JSON export and the source is trusted (it came from your own program, not the internet), `ast.literal_eval` parses it safely: import ast import json pythonish = "{'name': 'Ada', 'active': True, 'tags': ['x', 'y']}" # Safely evaluate the Python literal, then convert to real JSON obj = ast.literal_eval(pythonish) clean = json.dumps(obj, indent=2) print(clean) # Never use eval() here — it executes arbitrary code. # ast.literal_eval only accepts literals and raises on anything else. The boundary matters: `ast.literal_eval` is for **trusted data in Python literal syntax**. For JSON from third parties, fix the producer or reject the input — never reach for `eval()`, which will execute whatever the payload contains. If the string mostly looks like JSON but with a few single quotes, the safer normalization is to fix it at the source (JavaScript's `JSON.stringify`, a proper serializer, or a config format that actually supports single quotes such as YAML). Debugging JSON API Responses in Practice
The most common real-world task: you call an API and want to see what actually came back. Combine the pieces above into a small, reusable helper that never crashes on edge cases: import json import requests def pretty_api_response(resp): """Pretty-print a JSON API response, tolerating errors.""" if resp.status_code >= 400: print(f"HTTP — body follows") if not resp.content: print("(empty body)") return try: print(json.dumps(resp.json(), indent=2, ensure_ascii=False)) except json.JSONDecodeError as e: print(f"Not JSON: ") print("First 200 chars:", repr(resp.text[:200])) r = requests.get("https://api.example.com/users/1") pretty_api_response(r) The two guards do all the work: the emptiness check catches 204s and HEAD-style responses before they hit the parser, and the `repr()` fallback shows you HTML error pages or BOM bytes that a bare exception message would hide. For quick one-off checks without any code, pipe the same request through `python3 -m json.tool` or paste the body into the [ JSON Formatter ](https://devtoolshub.cloud/tools/json-formatter) , which reports the exact line and column of any parse error. Common Mistakes & How to Avoid Them
- **Leaving a trailing comma in hand-written JSON.** Python dicts allow `"}`, JSON does not. If you generate JSON by hand or convert Python literals to JSON by copy-paste, strip the final comma — or better, build the dict in code and let `json.dumps` serialize it correctly. - **Using single quotes in JSON data.** Only double quotes are valid around JSON keys and string values. Data copied from Python source, JavaScript object literals, or some config files carries single quotes — re-serialize it with `json.dumps(ast.literal_eval(s))` for trusted input, or fix the producer. - **Opening JSON files without encoding, or ignoring the BOM.** Files exported from Windows tools often start with a byte-order mark that breaks parsing at char 0. Always use `open(path, encoding="utf-8-sig")` for JSON files from unknown sources — it strips the BOM if present and behaves like plain UTF-8 otherwise. - **Parsing an empty response body.** A 204 or empty 200 response produces the unhelpful “Expecting value: line 1 column 1” error. Check `if not body.strip():` before parsing, and log the status code alongside the body when debugging APIs. - **Calling json.load on a string (or json.loads on a file).** `json.load('')` fails with a confusing AttributeError because the function expects a file object. Remember the rule: ends in `s` means string, no `s` means file object. Frequently Asked Questions
Is my data sent to a server when using the online formatter?
No. Our
JSON Formatter
runs entirely in your browser with JavaScript, so the text you paste
never leaves your machine. The same is true for the standard library
approach in this article: json.dumps and json.tool process data
locally in your Python process. You can check this yourself by
opening your browser network tab while formatting — you will see no
requests carrying your input.
Why does Python reject single quotes in JSON?
The JSON specification (RFC 8259) allows only double quotes around
keys and string values. Single quotes are a Python and JavaScript
convenience that JSON deliberately omits to keep parsers simple and
unambiguous. If your data uses single quotes, it is a Python literal
rather than JSON: parse it with ast.literal_eval and re-serialize
with json.dumps, or fix whatever produced it to emit real JSON.
What is the difference between json.load and json.loads?
The trailing s stands for string. json.loads parses a str or bytes
object you already have in memory, which is what you want for HTTP
response bodies. json.load reads from an open file object and is
shorthand for json.loads(f.read()). They raise the same exceptions
and accept the same parsing options, so the choice is purely about
where your input lives.
How do I pretty print JSON from an API response?
With requests, call json.dumps(r.json(), indent=2). With curl in a
terminal, pipe the output to python3 -m json.tool. If you are using
httpx or urllib, parse resp.text with json.loads first. For a quick
look without any code, paste the response body into the online
formatter, which also shows the line and column of any parse error
when the API returned something unexpected.
How do I validate a large JSON file?
For files that fit in memory, python3 -m json.tool data.json >
/dev/null validates and reports the first error with line and column
numbers. For files too big for RAM, read incrementally with a
streaming parser such as ijson, which validates and iterates item by
item without loading everything. In CI pipelines, validation costs
almost nothing compared to a downstream job failing on malformed
input, so run it early and fail fast.
**Related Tools:** [JSON Formatter](https://devtoolshub.cloud/tools/json-formatter) [URL Encoder](https://devtoolshub.cloud/tools/url-encoder) [Base64 Encoder / Decoder](https://devtoolshub.cloud/tools/base64) 原文:https://www.a8q9.cn/en/article/how-to-format-json-in-python-and-fix-common-errors-8cbe73.html