Convert dictionary to JSON in python

r = {'is_claimed': 'True', 'rating': 3.5} r = json.dumps(r) file.write(str(r['rating'])) 

I cannot access my data in json. What am I doing wrong?

 TypeError: string indices must be integers, not str 
+263
json python dictionary
Nov 04 '14 at 21:38
source share
3 answers

json.dumps() converts the dictionary into a str object, not a json (dict) object! so you need to load your string in a dict in order to use it using the json.loads() method

See json.dumps() as a save method and json.loads() as a retrieve method.

This is sample code that can 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'] #Output 3.5 type(r) #Output str type(loaded_r) #Output dict 
+413
Sep 28 '15 at 13:31 on
source share

json.dumps() returns a JSON string representation for a python dict. See documents

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

Did you mean 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'])) 
+35
Nov 04 '14 at 21:44
source share

No need to convert to string using json.dumps ()

 >>> f = open("t.txt",'w') >>> r = {'is_claimed': 'True', 'rating': 3.5} >>> f.write(r['is_claimed']) >>> f.write(r['rating']) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: expected a character buffer object 

should be a string to write to the file, but the rating value is float, so convert to string first, and then try. It works reliably.

+1
Nov 05 '14 at 7:44
source share



All Articles