How to convert a JSON string to a Python dictionary?
Published on Aug. 22, 2023, 12:17 p.m.
To convert a JSON string to a Python dictionary, you can use the json.loads()
method provided by the json
module.
Here’s an example:
import json
json_string = '{"name": "John", "age": 30, "city": "New York"}'
python_dict = json.loads(json_string)
print(python_dict)
This will print out the Python dictionary:
{'name': 'John', 'age': 30, 'city': 'New York'}
Note that json.loads()
only works with valid JSON strings. If the input string is not in proper JSON format, a json.JSONDecodeError
will be raised. Also, make sure that the keys in the JSON string are always enclosed in double quotes (” “), as single quotes are not valid in JSON.