To convert a JSON string to a dictionary in Python, you can use the `json.loads()` function from the `json` module. This allows you to parse a JSON string and convert it into a dictionary.
We can convert a JSON string to a dictionary in Python using the `json.loads()` function. This example demonstrates how to declare a JSON string, use the `json.loads()` function to convert the JSON string to a dictionary, and print the resulting dictionary.
For example,
json_string
that contains the JSON representation of a dictionary.import json
# Declare a JSON string
json_string = '{"1": "One", "2": "Two", "3": "Three"}'
# Convert the JSON string to a dictionary using json.loads()
my_dict = json.loads(json_string)
# Print the resulting dictionary
print('Dictionary from JSON string:')
for key, value in my_dict.items():
print(f'Key: {key}, Value: {value}')
Dictionary from JSON string: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three
We can convert a JSON string with complex values to a dictionary in Python using the `json.loads()` function. This example demonstrates how to declare a JSON string with complex values, use the `json.loads()` function to convert the JSON string to a dictionary, and print the resulting dictionary.
For example,
json_string
that contains the JSON representation of a dictionary with complex values.import json
# Declare a JSON string with complex values
json_string = '{"1": {"name": "John", "age": 30}, "2": {"name": "Jane", "age": 25}}'
# Convert the JSON string to a dictionary using json.loads()
my_dict = json.loads(json_string)
# Print the resulting dictionary
print('Dictionary from JSON string:')
for key, value in my_dict.items():
print(f'Key: {key}, Value: {value}')
Dictionary from JSON string: Key: 1, Value: {'name': 'John', 'age': 30} Key: 2, Value: {'name': 'Jane', 'age': 25}
In this tutorial, we learned How to Convert a JSON String to a Dictionary in Python language with well detailed examples.