pythonjsonformatter

Convert JSON to a Python dict

Use Python’s JSON parser when you have valid JSON text and need ordinary Python data structures.

Parse JSON with json.loads()

json.loads() accepts a JSON string and returns the matching Python value. A JSON object becomes a dictionary, and a JSON array becomes a list.

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.

When you have a JSON file rather than a string, open it and pass the file object to json.load(). Keep character encoding explicit with encoding="utf-8".

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.

By Python JSON Formatter ·