Learn to read JSON string in Python with the help of json.loads()
method which converts a given JSON string into a Python object.
For quick reference, below is the code which reads a JSON string into a Python object.
import json #JSON String json_string = '{"name": "Lokesh", "age": 38, "locations": ["India", "USA"]}' # Convert json string to object json_dict = json.loads(json_string) # Ready to use object further into the program print(json_dict)
1. json.loads() Method
The json.loads()
deserializes a given JSON string into a python dictionary/list object using these conversion rules.
JSON | Python |
---|---|
object |
|
array |
|
string |
|
number (int) |
|
number (real) |
float |
true |
True |
false |
False |
null |
None |
If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised.
2. Python Read JSON String Examples
Example 1: Reading a JSON String to Python List
In given example, we are reading a list of JSON objects into a Python list
.
import json # JSON String json_string = '[{"name": "Lokesh", "age": 38}, {"name": "Brian", "age": 48}]' # Read into Python list py_list = json.loads(json_string) print(type(py_list)) print(py_list)
Program output.
<class 'list'> [{'name': 'Lokesh', 'age': 38}, {'name': 'Brian', 'age': 48}]
Example 2: Reading a JSON String to Python Dictionary
In given example, we are reading a list of JSON objects into a Python list
.
import json # JSON String json_string = '{"name": "Lokesh", "age": 38}, {"name": "Brian", "age": 48}' # Read into Python list py_list = json.loads(json_string) print(type(py_list)) print(py_list)
Program output.
<class 'dict'> {'name': 'Lokesh', 'age': 38, 'locations': ['India', 'USA']}
Happy Learning !!
Leave a Reply