Open In App

Convert String to JSON Object – Python

Last Updated : 15 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The goal is to convert a JSON string into a Python dictionary, allowing easy access and manipulation of the data. For example, a JSON string like {“name”: “John”, “age”: 30, “city”: “New York”} can be converted into a Python dictionary, {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}, which allows you to access values by their keys. Let’s explore different methods to do this efficiently.

Using json.loads()

json.loads() method is the most commonly used function for parsing a JSON string and converting it into a Python dictionary. The method takes a string containing JSON data and deserializes it into a Python object. This is the most efficient way to handle JSON data in Python.

Python
import json

s = '{"name": "John", "age": 30, "city": "New York"}'
res= json.loads(s)

print(type(res),res)

Output
<class 'dict'> {'name': 'John', 'age': 30, 'city': 'New York'}

Explanation: loads() function stands for “load string,” and it parses the JSON string and converts it into a dictionary. This resulting dictionary is assigned to the variable res.

Using ast.literal_eval()

ast.literal_eval() function safely evaluates a string containing Python literals (including JSON-like structures) and converts it into an equivalent Python object. It’s safer than eval() because it only allows expressions containing Python literals, such as dictionaries, lists, numbers and strings.

Python
import ast

s = '{"name": "John", "age": 30, "city": "New York"}'
res = ast.literal_eval(s) 

print(type(res), res)

Output
<class 'dict'> {'name': 'John', 'age': 30, 'city': 'New York'}

Explanation: ast.literal_eval() function parses the string and converts it into a dictionary, ensuring that only literal expressions are evaluated.

Using eval()

eval() function evaluates a string as a Python expression and returns the result. While powerful, eval() is unsafe when working with untrusted input, as it can execute arbitrary code. It is generally not recommended for parsing JSON due to security risks but can still be used to convert a string that follows Python’s literal syntax into a dictionary.

Python
s = '{"name": "John", "age": 30, "city": "New York"}'

res = eval(s)

print(type(res), res)

Output
<class 'dict'> {'name': 'John', 'age': 30, 'city': 'New York'}

Explanation: eval(s) takes the string s, evaluates it as a Python expression and returns the result as a Python object.



Next Article
Practice Tags :

Similar Reads