JSON Encoding/Decoding with Python
For seamless data exchange and storage, converting Python dictionaries to JSON (JavaScript Object Notation) is a common requirement. However, unexpected errors can arise when attempting to access JSON data from a dictionary.
Error Encountered:
Consider the following code snippet:
<code class="python">r = {'is_claimed': 'True', 'rating': 3.5} r = json.dumps(r) file.write(str(r['rating']))</code>
When attempting to access the 'rating' key from the JSON string, a "TypeError: string indices must be integers, not str" error occurs. This error arises because json.dumps() converts the dictionary 'r' into a string, not an actual JSON object or dictionary.
Correct Approach:
To resolve this issue, utilize the json.loads() method to load the JSON string back into a dictionary. This allows you to access the 'rating' key as follows:
<code class="python">import json r = {'is_claimed': 'True', 'rating': 3.5} r = json.dumps(r) loaded_r = json.loads(r) print(loaded_r['rating'])</code>
Understanding the Distinction:
json.dumps() saves a dictionary as a string, while json.loads() retrieves it as a dictionary. Remember to use json.dumps() when serializing data and json.loads() when deserializing it.
The above is the detailed content of How to Avoid Errors When Accessing JSON Data from Python Dictionaries. For more information, please follow other related articles on the PHP Chinese website!