Parsing JSON in Python: json.loads() and json.load() Guide
Python's built-in json module makes parsing straightforward. This guide covers both parsing functions, custom type handling, and robust error handling patterns.
json.loads() vs json.load()
json.loads() (with an s for "string") accepts a string containing JSON and returns the parsed Python object. json.load() (without the s) reads from a file-like object. The two functions are equivalent in behavior but differ in input source: use loads() when you have a string, load() when reading from a file.
import json; data = json.loads('{"name": "Alice"}') returns {"name": "Alice"} as a Python dict. For a file: with open("data.json") as f: data = json.load(f). Both return the same type mapping: JSON object to dict, array to list, string to str, number to int or float, boolean to bool, null to None.
Handling JSON Type Mapping
Python's json module maps JSON numbers to Python int or float based on the presence of a decimal point or exponent. JSON booleans (true/false) map to Python True/False. JSON null maps to Python None. These mappings are straightforward but worth knowing to avoid type comparison bugs.
JSON does not have a type for dates, so dates in JSON are typically ISO 8601 strings. After parsing, convert date strings to Python datetime objects: datetime.fromisoformat(data["created_at"]).replace(tzinfo=timezone.utc). The json module provides no automatic date conversion — you handle it in application code.
Custom Object Decoding
json.loads() accepts an object_hook parameter — a callable that is invoked for every JSON object (dict) decoded. Use it to convert plain dicts to custom Python classes: json.loads(text, object_hook=lambda d: MyClass(**d)) converts every JSON object to a MyClass instance if its keys match.
For more complex type hierarchies, use a JSONDecoder subclass that overrides the decode() method. This gives you full control over how JSON values are converted to Python objects, including handling of nested custom types and type discrimination based on field values.
Error Handling for JSON Parsing in Python
json.loads() raises json.JSONDecodeError (a subclass of ValueError) when the input is not valid JSON. The exception includes the error message, the document string, and the position of the error. Wrap calls in try/except json.JSONDecodeError to handle failures gracefully.
For debugging parse errors, json.JSONDecodeError provides the .lineno, .colno, and .pos attributes for locating the error precisely. Print the raw string and these attributes together: f"Parse error at line {e.lineno}, col {e.colno}: {e.msg}" gives a clear diagnostic message.
Try JSON Parser Free Online
No sign-up required. 100% client-side — your data never leaves your browser.
Open JSON Parserarrow_forwardFrequently Asked Questions
How do I parse a JSON API response in Python?
With the requests library: response = requests.get(url); data = response.json(). The .json() method calls json.loads() on the response text automatically and raises an error if the response is not valid JSON.
Can Python parse JSON with comments?
Not with the built-in json module. Install the json5 package (pip install json5) to parse JSON5 files that contain comments. Alternatively, strip comments before passing to json.loads().
How do I parse a very large JSON file in Python efficiently?
Use the ijson library for streaming JSON parsing. ijson parses incrementally, letting you process array elements one at a time without loading the entire file into memory. Install with pip install ijson.