Converting JSON Strings to Dictionaries in Python
In Python, JavaScript Object Notation (JSON) data is frequently encountered as hierarchical structures within strings. To work with JSON data effectively, you may encounter the need to convert a JSON string into a Python dictionary, which is a native Python data structure.
Using json.loads()
The standard Python library provides the json module, which houses the function json.loads(). This function takes a JSON string and parses it into a Python object, typically a dictionary. For instance:
<code class="python">import json json_string = '{"name": "John Doe", "age": 30}' python_dict = json.loads(json_string)</code>
After executing this code, python_dict becomes a dictionary with two key-value pairs: "name" maps to "John Doe" and "age" maps to 30.
Case Study: Extracting Dictionary Values
Your example JSON string is a nested dictionary with a complex structure. To convert it into a dictionary and access its values, follow these steps:
<code class="python">import json json_string = '...' # Your JSON string here # Parse the JSON string json_dict = json.loads(json_string) # Retrieve the "title" value from the outermost dictionary title = json_dict['glossary']['title'] print(title) # Output: "example glossary"</code>
In this example, json_dict becomes a nested dictionary after parsing the JSON string. You can then use dictionary access notation to navigate through the levels and retrieve the desired value, assigned to the title variable.
Additional Considerations
The above is the detailed content of How to convert JSON strings to Python dictionaries using json.loads()?. For more information, please follow other related articles on the PHP Chinese website!