Skip to content

How to Convert String to JSON in Python

Learn how to parse JSON strings into Python dictionaries using json.loads(), handle common syntax errors, and safely process JSON data from APIs or files.

Parsing JSON strings into Python dictionaries is fundamental for working with web APIs, configuration files, and data interchange. Python's built-in json module provides secure and efficient parsing through the json.loads() function.

Parse JSON Strings with json.loads()

The json.loads() function (load string) converts a JSON-formatted string into a Python dictionary.

import json

json_string = '{"id": 1, "name": "Alice", "active": true}'

data = json.loads(json_string)

print(data)

print(data['name'])

print(type(data))

JSON to Python Type Mapping

JSON types automatically convert to their Python equivalents.

import json

json_string = '''
{
    "string": "hello",
    "integer": 42,
    "float": 3.14,
    "boolean": true,
    "null_value": null,
    "array": [1, 2, 3],
    "nested": {"key": "value"}
}
'''

data = json.loads(json_string)

print(type(data['boolean']))    # <class 'bool'>
print(type(data['null_value'])) # <class 'NoneType'>
print(type(data['array']))      # <class 'list'>
print(type(data['nested']))     # <class 'dict'>
JSON Type Python Type
string str
number (int) int
number (float) float
true / false True / False
null None
array list
object dict

Avoid Common JSON Syntax Errors

JSON has strict formatting requirements that differ from Python syntax.

Single Quotes Are Invalid

JSON requires double quotes for strings. Python dictionary syntax with single quotes is not valid JSON.

import json

invalid_json = "{'id': 1, 'name': 'Alice'}"

try:
    json.loads(invalid_json)
except json.JSONDecodeError as e:
    print(f"Error: {e}")

valid_json = '{"id": 1, "name": "Alice"}'
data = json.loads(valid_json)
print(data)

Trailing Commas Are Invalid

import json

invalid = '{"id": 1, "name": "Alice",}'

valid = '{"id": 1, "name": "Alice"}'

Handle Parsing Errors Gracefully

External data sources may provide malformed JSON. Always wrap parsing in error handling.

import json

def parse_json(raw_string: str) -> dict | None:
    """Safely parse JSON string with error handling."""
    try:
        return json.loads(raw_string)
    except json.JSONDecodeError as e:
        print(f"Invalid JSON at position {e.pos}: {e.msg}")
        return None

result = parse_json('{"status": "ok"}')
print(result)

result = parse_json("not valid json")
print(result)

Provide Default Values

import json

def parse_json_with_default(raw: str, default: dict = None) -> dict:
    """Parse JSON with fallback to default value."""
    if default is None:
        default = {}
    
    try:
        return json.loads(raw)
    except (json.JSONDecodeError, TypeError):
        return default

config = parse_json_with_default('{"theme": "dark"}')
print(config.get('theme'))

config = parse_json_with_default('invalid', {'theme': 'light'})
print(config.get('theme'))

Parse JSON from Files

Use json.load() (without the s) to read directly from file objects.

import json

with open('config.json', 'r') as file:
    config = json.load(file)

print(config)

Parse JSON Arrays

JSON arrays convert to Python lists. Top-level arrays are valid JSON.

import json

json_array = '[{"id": 1}, {"id": 2}, {"id": 3}]'

items = json.loads(json_array)

print(type(items))

for item in items:
    print(item['id'])

Output:

<class 'list'>
1
2
3

Convert Python Objects to JSON

Use json.dumps() for the reverse operation, converting Python objects to JSON strings.

import json

data = {
    'name': 'Alice',
    'scores': [95, 87, 91],
    'active': True
}

json_string = json.dumps(data)
print(json_string)

pretty_json = json.dumps(data, indent=2)
print(pretty_json)

Output:

{"name": "Alice", "scores": [95, 87, 91], "active": true}
{
  "name": "Alice",
  "scores": [
    95,
    87,
    91
  ],
  "active": true
}

Quick Reference

Operation Method Example
String → Dict json.loads(s) json.loads('{"a": 1}')
File → Dict json.load(f) json.load(open('data.json'))
Dict → String json.dumps(d) json.dumps({'a': 1})
Dict → File json.dump(d, f) json.dump(data, open('out.json', 'w'))

Conclusion

Use json.loads() to parse JSON strings into Python dictionaries. Always use double quotes in JSON, handle JSONDecodeError exceptions when processing external data, and never use eval() as an alternative because it introduces critical security vulnerabilities. For file operations, use json.load() and json.dump() to work directly with file objects.

Navigation