Accessing Data in Converted JSON Dictionaries
When attempting to convert a dictionary to JSON, you may encounter difficulties in accessing the data as the converted object is a string.
Consider the following example:
<code class="python">r = {'is_claimed': 'True', 'rating': 3.5} r = json.dumps(r) file.write(str(r['rating']))</code>
This code attempts to write the 'rating' field to a file after converting the dictionary to JSON. However, this results in a TypeError: string indices must be integers, not str.
The issue stems from the fact that json.dumps() converts the dictionary into a string representation, not a JSON object. To access the data, you must first load the string back into a dictionary using the json.loads() method.
Think of json.dumps() as a save method and json.loads() as a retrieve method. Here's an updated code sample:
<code class="python">import json r = {'is_claimed': 'True', 'rating': 3.5} r = json.dumps(r) loaded_r = json.loads(r) loaded_r['rating'] # Output 3.5 type(r) # Output str type(loaded_r) # Output dict</code>
Now, loaded_r is a dictionary, and you can access its fields as expected.
The above is the detailed content of How to Access Data from Converted JSON Dictionaries in Python?. For more information, please follow other related articles on the PHP Chinese website!