Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Convert String to JSON using Python?
In this article, we are going to learn how to convert a string to JSON in Python. JSON is a lightweight data interchange format that is used to read and write, and store data.
Usually, we receive JSON data in the form of a string. To process it using a Python program, we need to convert the JSON string into an object, which can be stored in Python dictionaries and lists. This conversion can be done by using functions provided by the Python JSON module.
Using Python json.loads() Function
The Python json.loads() function is used to convert the JSON-formatted string into a Python object. After parsing, this function returns a Python object, such as dictionaries, lists, etc, depending on the structure of the JSON string.
Syntax
Following is the syntax of Python json.loads() function −
json.loads(s)
Where s is the JSON string to be converted.
Converting JSON String to Dictionary
Let's look at the following example, where we are going to convert a JSON string into a Python dictionary ?
import json
json_string = '{"Car": "Chiron", "Engine": "6Stroke"}'
result = json.loads(json_string)
print(result)
print(type(result))
{'Car': 'Chiron', 'Engine': '6Stroke'}
<class 'dict'>
Converting JSON Array to List
In the following example, we are going to convert the JSON array string into a Python list ?
import json json_string = '["TP", "TutorialsPoint", "Tutorix"]' result = json.loads(json_string) print(result) print(type(result))
['TP', 'TutorialsPoint', 'Tutorix'] <class 'list'>
Converting Nested JSON Objects
Consider the following example, where we are going to convert the JSON string with nested objects to a Python dictionary ?
import json
json_string = '{"vehicle": {"car": "Bugatti", "Fuel-tank": 650}}'
result = json.loads(json_string)
print(result)
print(result['vehicle']['car'])
{'vehicle': {'car': 'Bugatti', 'Fuel-tank': 650}}
Bugatti
Error Handling
When working with JSON strings, it's important to handle potential errors. Invalid JSON format will raise a json.JSONDecodeError ?
import json
invalid_json = '{"Car": "Chiron", "Engine": 6Stroke}' # Missing quotes
try:
result = json.loads(invalid_json)
print(result)
except json.JSONDecodeError as e:
print(f"Error: {e}")
Error: Expecting value: line 1 column 26 (char 25)
Conclusion
The json.loads() function is the standard way to convert JSON strings to Python objects. Always handle potential JSON parsing errors with try-except blocks for robust applications.
