Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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

2 Answers

0 votes
by (106k points)

To Convert dictionary to JSON you can use the json.dumps() which converts a dictionary to str object, not a json(dict) object! so you have to load your str into a dict to use it by using json.loads() method.

 

Below is the code which will help you understand it more:

import json r = {'is_claimed': 'True', 'rating': 3.5}

r = json.dumps(r)

loaded_r = json.loads(r)

Loaded_r['rating']

type(r)

str type(loaded_r)

0 votes
by (20.3k points)

json.dumps() method returns the JSON string representation of the python dict. 

Have a look at the docs:

https://docs.python.org/2/library/json.html#json.dumps

You can't do r['rating'] because r is a string, not a dict anymore

Perhaps you meant something like

r = {'is_claimed': 'True', 'rating': 3.5}

json = json.dumps(r) # note i gave it a different name

file.write(str(r['rating']))

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
4 answers
0 votes
4 answers

Browse Categories

...