pythonjsonformatter

Convert a JSON string to a Python dict

json.loads() parses JSON text. A JSON object becomes a dict. A file and a requests response use different calls.

Parse a JSON string with json.loads()

To convert a JSON string to a dict in Python, pass the text to json.loads(). A JSON object becomes a dictionary. A JSON array becomes a list. This is the call for text you already hold in memory, including a request body you read yourself.

import json

text = '{"name": "Ada", "active": true, "tags": ["python"]}'
data = json.loads(text)
print(data["name"])  # Ada

The top-level result is not always a dict. Parsing ["Ada", "Lin"] returns a list; a JSON number returns an int or float. If the next step requires an object, check its type before accessing keys.

data = json.loads('["Ada", "Lin"]')
print(type(data).__name__)  # list

if not isinstance(data, dict):
    print("Expected a JSON object")

How JSON values map to Python

JSONPython
objectdict
arraylist
true / falseTrue / False
nullNone

Why json.loads() can fail

The input must already be JSON. A Python dict written as {'name': 'Ada', 'active': True} is not JSON because it uses single quotes and an uppercase boolean. The parser is correct to reject it. Do not wrap that string in eval().

try:
    data = json.loads('{"active": True}')
except json.JSONDecodeError as exc:
    print(f"Invalid JSON at line {exc.lineno}, column {exc.colno}")

Replace Python's True with JSON's true when the input is meant to be JSON. If the source is actually a pasted Python literal, convert that literal first; do not pass it straight to json.loads().

If parsing succeeds but returns a string, check for double-encoded JSON before trying to access object properties.

A file and a requests response are not strings you pass yourself

For a .json file, open it and call json.load(). The steps, including UTF-8 and a top-level array, are in read a JSON file into a dict. For a requests response, call response.json() instead of json.loads(response.text) unless you already need the raw text. That path is in requests JSON to dict.

By Python JSON Formatter ·