Home >Backend Development >Python Tutorial >How to Access Data from JSON Converted from Dictionary?
Accessing Data in JSON Converted from Dictionary
When attempting to access data from a JSON object converted from a dictionary, you may encounter issues as demonstrated in the following code:
r = {'is_claimed': 'True', 'rating': 3.5} r = json.dumps(r) file.write(str(r['rating']))
This code aims to write the rating value in the JSON object r to a file. However, an error occurs because json.dumps() returns a string representation of the dictionary, not a JSON object.
Solution: Loading JSON String into Dictionary
To access data from the JSON string, you need to load it back into a dictionary using json.loads(). This method retrieves the JSON object from the string.
import json r = {'is_claimed': 'True', 'rating': 3.5} r = json.dumps(r) # Save as string loaded_r = json.loads(r) # Retrieve as dictionary print(loaded_r['rating']) # Output: 3.5
Understanding json.dumps() and json.loads()
By understanding the difference between saving and retrieving JSON, you can access data from a dictionary that has been converted to and from a JSON string.
The above is the detailed content of How to Access Data from JSON Converted from Dictionary?. For more information, please follow other related articles on the PHP Chinese website!