Dev Ops Ranga
Dev Ops Ranga

Reputation: 213

Json value print TypeError: string indices must be integers, not str

I have below dictionary in python

 >>> dict = {"name":"myname", "class": "10", "score %": "60"}

I have converted from dictionary to json format like below

>>> json_format = json.dumps(dict)
>>> print json_format
{"score %": "60", "name": "myname", "class": "10"}

I am trying to get value of key from json_format variable:

  >>> print json_format["name"]

I am getting below error:

Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
 TypeError: string indices must be integers, not str

Please help me where i am doing mistake.

Upvotes: 1

Views: 1544

Answers (1)

Saket Khandelwal
Saket Khandelwal

Reputation: 347

json.dumps() returns the string representation so you can't access it like a json datatype.

You need to do something like this:

import json
dict = {"name":"myname", "class": "10", "score %": "60"}
json_format = json.dumps(dict)

If you check the json_format type():

print(type(json_format))

Output:

<class 'str'>

So you need to do this:

json_format = json.loads(json_format)
print(json_format["name"])

Upvotes: 1

Related Questions