DEV Community

kingfujing
kingfujing

Posted on Originally published at devtoolshub.cloud

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
double quotes
β€” is famously cryptic when you just want to know
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.
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ 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:
Enter fullscreen mode Exit fullscreen mode
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)
Enter fullscreen mode Exit fullscreen mode
      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.
Enter fullscreen mode Exit fullscreen mode

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:
Enter fullscreen mode Exit fullscreen mode
# 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
Enter fullscreen mode Exit fullscreen mode
      `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`.
Enter fullscreen mode Exit fullscreen mode

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:
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode
      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.
Enter fullscreen mode Exit fullscreen mode

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`:
Enter fullscreen mode Exit fullscreen mode
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))
Enter fullscreen mode Exit fullscreen mode
      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.
Enter fullscreen mode Exit fullscreen mode

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:
Enter fullscreen mode Exit fullscreen mode
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('')
Enter fullscreen mode Exit fullscreen mode
      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.
Enter fullscreen mode Exit fullscreen mode

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:
Enter fullscreen mode Exit fullscreen mode
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]))
Enter fullscreen mode Exit fullscreen mode
      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.
Enter fullscreen mode Exit fullscreen mode

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:
Enter fullscreen mode Exit fullscreen mode
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.
Enter fullscreen mode Exit fullscreen mode
      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).
Enter fullscreen mode Exit fullscreen mode

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:
Enter fullscreen mode Exit fullscreen mode
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)
Enter fullscreen mode Exit fullscreen mode
      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.
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)