Use json.loads(text) when the string is valid JSON (double-quoted keys/strings, true/false/null), or ast.literal_eval(text) when the string is formatted as a Python literal ({'key': True, 'count': None} with single quotes, tuples, or Python booleans)—never eval(), which executes arbitrary code and creates a critical security vulnerability.
Basic Example
import ast
import json
# 1. Recommended for JSON strings (double quotes, true/false/null):
json_str = '{"user": "alice", "active": true, "score": null}'
data_from_json = json.loads(json_str)
print(data_from_json)
# Output: {'user': 'alice', 'active': True, 'score': None}
# 2. Recommended for Python dict literal strings (single quotes, True/False/None):
py_literal_str = "{'user': 'alice', 'active': True, 'tags': ('admin', 'ops')}"
data_from_literal = ast.literal_eval(py_literal_str)
print(data_from_literal)
# Output: {'user': 'alice', 'active': True, 'tags': ('admin', 'ops')}
# 3. Validate that the parsed result is actually a dict (not a list, int, or tuple):
if not isinstance(data_from_literal, dict):
raise TypeError(f"Expected dict, got {type(data_from_literal).__name__}")
Key Details & Edge Cases
- Never use
eval(text)on untrusted or external strings:eval("__import__('os').system('rm -rf /')")executes arbitrary Python expressions immediately. Bothjson.loads()andast.literal_eval()parse only static data structures without executing functions, attribute lookups, or imports.
ast.literal_eval()vs.json.loads()syntax differences:json.loads()rejects single-quoted keys/strings ({'a': 1}), trailing commas ({"a": 1,}), PythonTrue/False/None, and tuples(1, 2)—raisingjson.JSONDecodeError.ast.literal_eval()rejects lowercase JSONtrue/false/null—raisingValueError: malformed node or string(because Python treats lowercasetrueas an unknown variable identifier, not a literal).
- Always check
isinstance(result, dict)after parsing:- Both
json.loads("[1, 2, 3]")andast.literal_eval("(1, 2)")succeed cleanly and return alistortupleinstead of adict. Verifyisinstance(result, dict)before calling.get()or key indexing.
- Both
- Exceptions raised on malformed input (
try / except):json.loads()raisesjson.JSONDecodeError(a subclass ofValueError).ast.literal_eval()raisesValueError,SyntaxError,TypeError,MemoryError, orRecursionError(for deeply nested brackets like"{" * 5000). Catch(ValueError, SyntaxError, TypeError)when parsing untrusted strings withast.literal_eval().
- Avoid naive
.replace("'", '"')hacks to convert Python dicts into JSON:- Running
py_str.replace("'", '"')corrupts strings containing apostrophes ("O'Reilly"becomes invalid JSON"O"Reilly") and fails onTrue/False/None. Useast.literal_eval()directly on Python-formatted strings instead.
- Running
Comparison of String-to-Dictionary Parsing Methods in Python
| Method | Module | Accepts Single Quotes & True/None? |
Accepts JSON true/false/null? |
Safe Against Code Execution? | Best Used When |
|---|---|---|---|---|---|
json.loads(s) (Fastest & Standard) |
json (stdlib) |
No | Yes | Yes | Parsing API responses, config strings, or serialized JSON payloads. |
ast.literal_eval(s) |
ast (stdlib) |
Yes | No | Yes | Parsing Python str(my_dict) outputs, log dumps, or literal configs with True/None/tuples. |
yaml.safe_load(s) |
pyyaml (3rd-party) |
Yes | Yes | Yes | Parsing hybrid or unquoted YAML/JSON-like strings (slower; coerces yes/no to bools). |
eval(s) (Unsafe) |
Built-in | Yes | No | No (Remote Code Execution risk) | Never—always replace with ast.literal_eval() or json.loads(). |
You must log in or register to comment.
