stringtojson.
STRING TO JSON

Convert a string to JSON in Python with json.loads

To convert a JSON string in Python, pass it to json.loads() from the standard library. It returns a dict for a JSON object, a list for a JSON array, and a matching Python value for anything else.

Each example runs on its own with Python 3 and no extra packages. The outputs were checked with Python 3.11 and 3.14.

Parse a JSON string into a dict

Import the json module, pass the text to json.loads(), and read keys from the result as you would from any dictionary.

Python
import json

text = '{"order": "A-1042", "quantity": 2, "paid": true, "coupon": null}'
data = json.loads(text)

print(type(data))  # <class 'dict'>
print(data["order"])  # A-1042
print(data["quantity"] + 1)  # 3
print(data)  # {'order': 'A-1042', 'quantity': 2, 'paid': True, 'coupon': None}

The last line shows how Python displays a dict: single quotes, True and None. That display is not JSON. When you need JSON text again, use json.dumps(), covered below.

What type does json.loads return?

The top-level value decides the type. A valid JSON document does not have to be an object, so check what you received before you index into it.

JSON valuePython type
objectdict
arraylist
stringstr
number without a fraction or exponentint
number with a fraction or exponentfloat
true and falseTrue and False
nullNone
Python
import json

for text in ['[1, 2]', '"hello"', '42', '3.5', 'true', 'null']:
    value = json.loads(text)
    print(text, '->', repr(value), type(value).__name__)
Output
[1, 2] -> [1, 2] list
"hello" -> 'hello' str
42 -> 42 int
3.5 -> 3.5 float
true -> True bool
null -> None NoneType

Python also accepts NaN, Infinity and -Infinity. These are not valid JSON, so another parser may reject a document that Python reads.

Parse a JSON array string into a list

A JSON array becomes a Python list, and each object inside it becomes a dict.

Python
import json

text = '[{"sku": "A1", "qty": 2}, {"sku": "B7", "qty": 1}]'
items = json.loads(text)

print(len(items))  # 2
print(items[0]["sku"])  # A1
print(sum(item["qty"] for item in items))  # 3

If your code expects a list, check isinstance(items, list) first. Looping over a dict by mistake walks its keys, and the error appears a few lines later.

json.loads vs json.load, and json.dumps

Read the s in loads as "string". Use json.loads() for text you already hold in a variable and json.load() for an open file. The first statement writes a sample file to read.

Python
import json
from pathlib import Path

Path("order.json").write_text('{"order": "A-1042", "quantity": 2}', encoding="utf-8")

with open("order.json", encoding="utf-8") as file:
    data = json.load(file)

print(data["quantity"])  # 2

Pass the encoding explicitly. Without it, open() uses the platform default, which is not UTF-8 on every system.

json.dumps() goes the other way and turns a Python value into JSON text. json.dump() writes that text to a file.

Python
import json

data = {"city": "Zürich", "tags": ["new", "paid"], "note": None}

print(json.dumps(data))
print(json.dumps(data, indent=2, ensure_ascii=False))
Output
{"city": "Z\u00fcrich", "tags": ["new", "paid"], "note": null}
{
  "city": "Zürich",
  "tags": [
    "new",
    "paid"
  ],
  "note": null
}

By default, dumps() escapes every non-ASCII character. ensure_ascii=False keeps them readable, and indent=2 adds line breaks. A round trip can change the data: tuples come back as lists, and dict keys become strings, so {1: "a"} returns as {'1': 'a'}.

Catch json.JSONDecodeError

Invalid text raises json.JSONDecodeError, a subclass of ValueError. Its attributes tell you where parsing stopped: msg holds the message, lineno and colno count from 1, and pos is a zero-based index into the string.

Python
import json

text = "{'order': 'A-1042'}"

try:
    data = json.loads(text)
except json.JSONDecodeError as error:
    print(error)
    print(error.msg)
    print(error.lineno, error.colno, error.pos)
Output
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
Expecting property name enclosed in double quotes
1 2 1

Log the position so you can find the character quickly. Do not branch on the message text: it can change between Python versions, as the trailing comma section shows.

A TypeError is a different problem. It means the argument is not text at all.

Python
import json

data = {"status": "ok"}

try:
    json.loads(data)
except TypeError as error:
    print(error)  # the JSON object must be str, bytes or bytearray, not dict

The value has already been parsed, so use it directly.

Single quotes mean Python text, not JSON

The text in the error example above looks like a dict because it was probably produced by print() or str() on one. JSON requires double quotes around keys and strings, and it spells its literals true, false and null.

Fix this where the text is produced: write it with json.dumps(). Replacing every single quote with a double quote is fragile, because a value such as it's contains an apostrophe.

If you must read Python-literal text from a source you trust, such as a log your own program wrote, ast.literal_eval can read it without running code. It is not a JSON parser. It rejects true and null, and the Python documentation advises against calling it on untrusted data. Never use eval() for this.

Python
import ast
import json

text = "{'order': 'A-1042', 'paid': True}"
value = ast.literal_eval(text)

print(json.dumps(value))  # {"order": "A-1042", "paid": true}

Trailing commas, comments and line breaks

JSON allows no comma after the last item and has no comment syntax. Python's parser enforces both rules.

Invalid JSON
{"tags": ["new", "paid",]}
Valid JSON
{"tags": ["new", "paid"]}

For the invalid version, Python 3.14 reports Illegal trailing comma before end of array: line 1 column 24 (char 23). Python 3.11 reports Expecting value: line 1 column 25 (char 24) at the closing bracket. A // comment after a complete document produces an Extra data error instead.

A raw line break inside a quoted string gives Invalid control character at. Passing strict=False makes json.loads() accept it, but the producer should write \n instead. Fixing common JSON errors covers these problems with more examples.

When json.loads returns a string

If json.loads() gives you a str when you expected a dict, the payload was probably encoded twice. Each json.dumps() call adds a layer, and each json.loads() call removes one.

Python
import json

inner = json.dumps({"order": "A-1042", "quantity": 2})
text = json.dumps(inner)
print(text)  # "{\"order\": \"A-1042\", \"quantity\": 2}"

first = json.loads(text)
print(type(first))  # <class 'str'>

second = json.loads(first)
print(second["quantity"])  # 2

Calling loads() twice works here because you know there are two layers. In application code, find and remove the extra dumps() call rather than unwrapping in a loop. A loop can also turn a value that is meant to stay the string "123" into a number. Escaped and double-encoded JSON explains the backslashes in more detail.

Parse bytes from an HTTP response

json.loads() accepts bytes and bytearray as well as str, as long as the bytes are UTF-8, UTF-16 or UTF-32. You can pass a response body straight in.

Python
import json

body = b'{"status": "ok", "count": 3}'
data = json.loads(body)

print(data["count"])  # 3

With urllib.request, response.read() returns bytes like these. The third-party requests library goes one step further: response.json() parses the body and returns the dict. Passing that result to json.loads() again causes the TypeError shown earlier.

Keep large integers and decimals exact

Python integers have no fixed size, so json.loads() keeps long IDs exact. JavaScript's JSON.parse rounds the same value, as described in why a large JSON number can change after parsing. Decimal fractions behave differently: they become binary floats by default. Pass parse_float=decimal.Decimal when amounts must keep their exact decimal value.

Python
import decimal
import json

text = '{"id": 9007199254740993, "rate": 0.1}'

plain = json.loads(text)
print(plain["id"])  # 9007199254740993
print(plain["rate"] * 3)  # 0.30000000000000004

exact = json.loads(text, parse_float=decimal.Decimal)
print(repr(exact["rate"]))  # Decimal('0.1')
print(exact["rate"] * 3)  # 0.3

json.dumps() cannot write a Decimal by default and raises TypeError. Decide whether the receiving system expects a number or a string before you choose a conversion.

Inspect the payload before writing code

When a payload fails in Python, paste it into the String to JSON converter first. JSON Validator reports the error position, and String → JSON unwraps a quoted payload so you can see the object inside. The converter runs in your browser. It uses JavaScript numbers, so a very long integer can display rounded there even though Python reads it exactly.

For the general approach, see how to convert a string to JSON. For every parameter of loads() and dumps(), see the Python json module documentation.