How to Convert String to JSON in Python
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)
# Output: {'id': 1, 'name': 'Alice', 'active': True}
print(data['name'])
# Output: Alice
print(type(data))
# Output: <class 'dict'>
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: Single quotes
invalid_json = "{'id': 1, 'name': 'Alice'}"
try:
json.loads(invalid_json)
except json.JSONDecodeError as e:
print(f"Error: {e}")
# Output: Error: Expecting property name enclosed in double quotes
# ✅ Valid: Double quotes
valid_json = '{"id": 1, "name": "Alice"}'
data = json.loads(valid_json)
print(data)
# Output: {'id': 1, 'name': 'Alice'}
Trailing Commas Are Invalid
import json
# ❌ Invalid: Trailing comma
invalid = '{"id": 1, "name": "Alice",}'
# ✅ Valid: No trailing comma
valid = '{"id": 1, "name": "Alice"}'
If you're working with Python dict-like strings (single quotes), you may be tempted to use eval(). Never do this: it executes arbitrary code and creates severe security vulnerabilities.
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
# Valid JSON
result = parse_json('{"status": "ok"}')
print(result)
# Output: {'status': 'ok'}
# Invalid JSON
result = parse_json("not valid json")
print(result)
# Output: Invalid JSON at position 0: Expecting value
# None
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
# Returns parsed data
config = parse_json_with_default('{"theme": "dark"}')
print(config.get('theme'))
# Output: dark
# Returns default on failure
config = parse_json_with_default('invalid', {'theme': 'light'})
print(config.get('theme'))
# Output: light
Parse JSON from Files
Use json.load() (without the s) to read directly from file objects.
import json
# Read JSON from file
with open('config.json', 'r') as file:
config = json.load(file)
print(config)
Remember the distinction: json.loads() parses a string, while json.load() reads from a file object.
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))
# Output: <class 'list'>
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
}
# Convert to JSON string
json_string = json.dumps(data)
print(json_string)
# Output: {"name": "Alice", "scores": [95, 87, 91], "active": true}
# Pretty print with indentation
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.