← Home · Blog

How to Parse JSON in Python — Complete Guide

Published: July 10, 2025 · 7 min read

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.

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.

Format and Validate JSON Online

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

More Articles

How to Parse JSON in JavaScript

How to Flatten Nested JSON

5 Common JSON Errors and How to Fix Them

What is JSON — A Simple Explanation

← All Articles · Home · About · Privacy Policy