How do I convert a JSON string to an object in Python?

Dark navy cover card with the title 'How do I convert a JSON string to an object in Python?' in white and a green accent bar

To convert a JSON string to an object in Python, import the built-in json module and call json.loads(text). It returns a dict for a JSON object (or a list for an array), which you read with keys like data["name"]. If you want attribute access or your own class instead, pass an object_hook function.

How to convert a JSON string to an object in Python with json.loads

json.loads is the standard way to convert a JSON string into a Python object, and it ships with Python. The json module docs say it deserializes a str, bytes or bytearray containing a JSON document into a Python object.

import json

text = '{"name": "Asha", "admin": true, "tags": ["ops", "billing"], "manager": null}'
data = json.loads(text)

print(data["name"])     # Asha
print(data["admin"])    # True
print(type(data))       # <class 'dict'>

If your text comes from an HTTP response as bytes, you can pass the bytes directly without decoding them first.

How JSON types map to Python types

Each JSON value turns into a fixed Python type. The docs list this table for decoding:

JSON Python
object dict
array list
string str
number (int) int
number (real) float
true / false True / False
null None

Two details catch people. First, JSON object keys are always strings. The docs note that when a dict goes to JSON, all keys become strings, so a round trip "may not equal the original one." A dict like {1: "a"} comes back as {"1": "a"}.

Second, the decoder accepts NaN, Infinity and -Infinity, which the docs call "outside the JSON spec." Python will parse text that a browser rejects. Our post on NaN and Infinity in JSON covers what to do about that.

Reading JSON from a file with json.load

For a file, use json.load (no "s") and hand it the open file object. It reads a text or binary file that supports .read() and parses the contents.

import json

with open("config.json", encoding="utf-8") as f:
    config = json.load(f)

The "s" in loads stands for string. Mixing them up gives a confusing error: json.loads(f) complains about the type, and json.load(text) fails because a string has no .read() method.

Getting dot access with SimpleNamespace

To read fields as attributes, like data.user.name, convert each JSON object into a SimpleNamespace with object_hook. The docs describe object_hook as a function called with every decoded JSON object, whose return value is used in place of the dict. SimpleNamespace is a simple object that gives attribute access to its contents.

import json
from types import SimpleNamespace

text = '{"user": {"name": "Asha", "team": {"name": "Ops"}}}'
data = json.loads(text, object_hook=lambda d: SimpleNamespace(**d))

print(data.user.team.name)   # Ops

The hook runs from the inside out, so nested objects become namespaces too. One limitation: a key that isn't a valid Python name, such as "first-name", can only be read with getattr(data, "first-name").

Converting JSON into a dataclass

For typed code, map the dict into a dataclass, which generates __init__() and __repr__() for you. Unpack the parsed dict into the constructor:

import json
from dataclasses import dataclass

@dataclass
class User:
    name: str
    admin: bool

user = User(**json.loads('{"name": "Asha", "admin": false}'))
print(user)   # User(name='Asha', admin=False)

This is strict in a useful way. An extra key in the JSON raises a TypeError for an unexpected keyword argument, so you notice when the payload changes. It does not check types, though: "admin": "yes" is accepted as a string.

My take: start with plain dicts, and move to a dataclass once the same payload shape is read in more than one place. SimpleNamespace is handy in a notebook, but in production code I want a class that names its fields.

Debugging a JSONDecodeError

When the text isn't valid JSON, json.loads raises json.JSONDecodeError. The docs say it is a subclass of ValueError and carries msg, doc, pos, lineno and colno, so you can point straight at the broken character.

The most common case I see is text produced by printing a Python dict instead of dumping it:

import json

bad = "{'name': 'Asha'}"   # what print(my_dict) writes
try:
    json.loads(bad)
except json.JSONDecodeError as e:
    print(e.msg, "at line", e.lineno, "column", e.colno)

The error reads Expecting property name enclosed in double quotes. RFC 8259 requires strings to start and end with double quotation marks, and the literals true, false and null must be lowercase. So Python's True and None in a printed dict fail too.

The fix belongs in the code that writes the text: use json.dumps(obj) there, not str(obj). Patching single quotes with .replace breaks as soon as a value contains an apostrophe. To see where a long payload breaks, paste it into a JSON validator, which shows the parse error in the browser. For more on the quoting rule, read why JSON requires double quotes.

Keeping exact decimals and limiting input size

Prices and other exact amounts should not become floats. Pass parse_float=decimal.Decimal and the parser builds a Decimal from each fractional number; the docs suggest exactly this use.

import json
from decimal import Decimal

order = json.loads(response_text, parse_float=Decimal)
print(type(order["total"]))   # <class 'decimal.Decimal'>

Also check the size of anything you parse from outside. The docs warn that a malicious JSON string "may cause the decoder to consume considerable CPU and memory resources" and recommend limiting the size of data you parse. A size check on the request body before json.loads is enough for most APIs.

If you're going the other way, see how to pretty print JSON in Python, and for the JavaScript side of the same job, JSON.stringify vs JSON.parse.

FAQ

What does json.loads return in Python?

It returns whatever the top-level JSON value is: a dict for a JSON object, a list for an array, and str, int, float, True, False or None for the simple values.

What is the difference between json.load and json.loads?

json.loads takes a string, bytes or bytearray. json.load takes a file object opened for reading and parses its contents.

How do I access JSON fields with dot notation in Python?

Pass object_hook=lambda d: SimpleNamespace(**d) to json.loads. Every JSON object then becomes a SimpleNamespace, so you can write data.user.name.

Why does json.loads fail on single quotes?

JSON strings must use double quotes, so text like {'name': 'Asha'} is not JSON. It usually comes from printing a Python dict. Fix the producer to write json.dumps output instead.

How do I keep decimals exact when parsing JSON in Python?

Pass parse_float=decimal.Decimal to json.loads. Numbers with a fraction then become Decimal values instead of floats.

Sources