โ† Home ยท Blog

How to Parse JSON in Python โ€” Complete Guide

Published: July 10, 2025 ยท Last updated: September 7, 2026 ยท 7 min read ยท By JSON Suite Team

Python makes working with JSON straightforward thanks to its built-in json module. Whether you're consuming REST APIs, reading config files, or storing structured data, this guide covers everything you need to know. Not familiar with JSON? Check out our beginner's guide to JSON first.

The json Module โ€” No Install Required

Python ships with a json module in the standard library. You don't need to install anything.

import json

The four functions you'll use most:

  • json.loads() โ€” parse a JSON string into a Python object
  • json.dumps() โ€” convert a Python object to a JSON string
  • json.load() โ€” read JSON directly from a file
  • json.dump() โ€” write JSON directly to a file

Parsing a JSON String (json.loads)

json.loads() takes a JSON-formatted string and returns the equivalent Python data structure.

import json json_string = '{"name": "Alice", "age": 30, "active": true}' data = json.loads(json_string) print(data["name"]) # Alice print(data["age"]) # 30 print(type(data)) # <class 'dict'>

JSON types map to Python types as follows:

JSON TypePython Type
objectdict
arraylist
stringstr
number (int)int
number (float)float
true / falseTrue / False
nullNone

Converting Python to JSON (json.dumps)

Use json.dumps() to serialize a Python dict or list into a JSON string.

import json data = {"name": "Bob", "scores": [95, 87, 92], "passed": True} # Compact output print(json.dumps(data)) # {"name": "Bob", "scores": [95, 87, 92], "passed": true} # Pretty-printed with indentation print(json.dumps(data, indent=2)) # Sort keys alphabetically print(json.dumps(data, indent=2, sort_keys=True))

Reading JSON from a File (json.load)

import json with open("data.json", "r", encoding="utf-8") as f: data = json.load(f) print(data["users"][0]["name"])

Always specify encoding="utf-8" to avoid issues with special characters on Windows.

Writing JSON to a File (json.dump)

import json users = [ {"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"} ] with open("output.json", "w", encoding="utf-8") as f: json.dump(users, f, indent=2, ensure_ascii=False)

The ensure_ascii=False option preserves non-ASCII characters like accents and emoji instead of escaping them.

Working with Nested JSON

import json response = ''' { "status": "ok", "data": { "user": { "id": 42, "profile": { "displayName": "Alice W.", "location": "Berlin" } } } } ''' obj = json.loads(response) # Access nested values with chained keys name = obj["data"]["user"]["profile"]["displayName"] print(name) # Alice W. # Use .get() for safe access (returns None instead of KeyError) city = obj["data"]["user"]["profile"].get("city", "Unknown") print(city) # Unknown

Error Handling

Always wrap json.loads() in a try/except when dealing with untrusted input.

import json raw = '{"name": "Alice", "age": }' # broken JSON try: data = json.loads(raw) except json.JSONDecodeError as e: print(f"JSON error: {e.msg} at line {e.lineno}, column {e.colno}")

Parsing JSON from an API Response

import json import urllib.request url = "https://api.github.com/repos/python/cpython" with urllib.request.urlopen(url) as response: data = json.loads(response.read().decode("utf-8")) print(data["stargazers_count"]) # current star count

If you use the popular requests library, it has a built-in .json() method on the response object that does this in one step.

Common JSON Operations in Python

Beyond basic parsing, you'll often need to compare JSON documents, convert between formats, or handle deeply nested structures. For comparing two JSON files programmatically, see our JSON comparison guide. If you're working with deeply nested data, our guide to flattening nested JSON shows practical techniques. Watch out for the most common JSON errors that can cause parsing failures.

Format and Validate JSON Online

Before working with a JSON payload in Python, it helps to inspect it visually first. Try our free tools:

  • JSON Formatter โ€” pretty-print and validate JSON instantly
  • JSON Tree Viewer โ€” explore nested JSON as a collapsible tree
  • Fix JSON โ€” auto-repair broken JSON before passing it to Python

Related Tools

Parse, format, and validate JSON with these free online tools:

More Articles

How to Parse JSON in JavaScript

How to Flatten Nested JSON

10+ Common JSON Errors and How to Fix Them

What is JSON โ€” A Complete Guide