For a string containing JSON, use Python’s json.loads(). When the JSON’s top-level value is an object, it returns a Python dictionary. JSON arrays and other top-level values decode to different Python types.
1. Parse a JSON string with json.loads()
This is the standard choice when you already have JSON text. Python’s json module documentation describes json.loads() as deserializing a JSON document supplied as a string, bytes, or bytearray into a Python object.
import json
json_text = '{"name": "Ada", "active": true, "scores": [10, 12]}'
data = json.loads(json_text)
print(data["name"]) # Ada
print(type(data)) # <class 'dict'>
JSON syntax uses double quotes around strings and object keys, and the literals true, false, and null. Python converts these to True, False, and None when decoding.
Check the decoded type before treating it as a dictionary
The result depends on the JSON value at the document’s top level. A JSON object becomes a Python dict, but an array becomes a list; a string, integer, real number, boolean, or null becomes str, int, float, bool, or None, respectively. Only an object at the top level produces a dictionary.
#1 Best Overall
If your code expects a dictionary, check the input’s shape or verify the result before using string keys:
data = json.loads(json_text)
if isinstance(data, dict):
print(data["name"])
else:
raise TypeError("Expected a JSON object at the top level")
2. Decode explicitly with JSONDecoder
If you need to work with the decoder object directly, create a JSONDecoder and call its decode() method. For ordinary parsing, it gives you the same kind of decoded Python value as json.loads().
Rank #2
import json
decoder = json.JSONDecoder()
data = decoder.decode(json_text)
3. Transform objects with object_hook
Use object_hook when a JSON object has a known shape that should become another Python value. The function receives each decoded object as a dictionary and returns the value that should replace it. For example, tagged point objects can be turned into coordinate tuples:
import json
def object_hook(obj):
if obj.get("__type__") == "point":
return (obj["x"], obj["y"])
return obj
json_text = '{"location": {"__type__": "point", "x": 3, "y": 4}}'
data = json.loads(json_text, object_hook=object_hook)
print(data["location"]) # (3, 4)
4. Handle object members as ordered pairs with object_pairs_hook
object_pairs_hook receives each JSON object’s members as an ordered list of pairs. It can return a dictionary or another representation you choose. For example, passing dict builds a dictionary from those pairs:
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsdata = json.loads(json_text, object_pairs_hook=dict)
If you provide both object_pairs_hook and object_hook, object_pairs_hook takes priority.
5. Choose numeric types with parsing hooks
Use parse_float or parse_int when the default Python numeric type is not the right fit. The hooks receive a JSON number’s text and let you apply a different conversion policy. For example, decoding decimal values as Decimal can avoid converting them to binary floating-point numbers:
import json
from decimal import Decimal
json_text = '{"price": 12.50}'
data = json.loads(json_text, parse_float=Decimal)
print(data["price"]) # Decimal('12.50')
Use these hooks for a specific numeric requirement; ordinary JSON numbers need no customization.
Use json.load() for a file, not a string
The distinction is the input: json.loads(text) parses JSON text, while json.load(file) reads and parses a file-like object.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Best Value
import json
with open("data.json", encoding="utf-8") as file:
data = json.load(file)
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Fix common parsing errors
Invalid JSON raises JSONDecodeError
If the text is malformed, json.loads() raises json.JSONDecodeError. Inspect the original input and the exception’s location details to find the problem.
Python-looking text may not be JSON
A string such as {'name': 'Ada'} uses single quotes and is a Python-style representation, not valid JSON. JSON requires double quotes around strings and keys. If the source is meant to be JSON, correct its serialization rather than passing it to eval(); eval() executes Python expressions and is not a JSON parser.
Python accepts some non-standard numeric constants
Python’s JSON decoder accepts NaN, Infinity, and -Infinity by default, although these are outside the JSON specification. If strict standards compliance matters, account for these values rather than assuming the default decoder rejects them.
Very large integer strings can be limited
Since Python 3.11, the default integer-parsing path uses the interpreter’s integer-string length limitation as a denial-of-service mitigation. This matters mainly when handling untrusted input or unusually large numeric values.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




