r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
file.write(str(r['rating']))
I am not able to access my data in the JSON. What am I doing wrong?
TypeError: string indices must be integers, not str
Answers
The error you’re encountering is due to the fact that after you call json.dumps(r)
, r
becomes a JSON-formatted string, not a dictionary. When you then try to access r['rating']
, it raises a TypeError
because strings can only be indexed using integers.
To fix this, you should first deserialize the JSON string back into a dictionary using json.loads()
, or directly access the original dictionary before converting it to JSON. Here are two ways to do it:
Option 1: Accessing the Original Dictionary
If you still have access to the original dictionary, you can write the rating
directly without converting it to JSON:
import json
r = {'is_claimed': 'True', 'rating': 3.5}
file.write(str(r['rating'])) # Access the rating directly
Option 2: Deserialize the JSON String
If you need to work with the JSON string for other reasons, deserialize it back into a dictionary:
import json
r = {'is_claimed': 'True', 'rating': 3.5}
r_json = json.dumps(r) # Convert to JSON string
# Deserialize back to a dictionary
r_dict = json.loads(r_json)
# Now you can access the 'rating'
file.write(str(r_dict['rating'])) # Access the rating from the dictionary
Summary
- Option 1 is simpler if you don’t need the JSON format afterward.
- Option 2 allows you to keep the JSON representation but requires you to convert it back to a dictionary to access individual fields.