Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting dictionary to JSON

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 
like image 730
sheetal_158 Avatar asked Nov 04 '14 21:11

sheetal_158


People also ask

Can dictionary be converted to JSON?

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.

How do you convert a Python dictionary to JSON?

1) Using dumps() function Python possesses a default module, 'json,' with an in-built function named dumps() to convert the dictionary into a JSON object by importing the "json" module. "json" module makes it easy to parse the JSON strings which contain the JSON object.

How do I save a dictionary to JSON?

To save the dictionary to JSON format, we will need the file object of the . json file and the dictionary that we need to save and pass them to the dump() method. We can also load the saved dictionary from the . json file using the load() method of the pickle library.

How do you represent a dictionary in JSON?

Introducing JSON JSON is a way of representing Arrays and Dictionaries of values ( String , Int , Float , Double ) as a text file. In a JSON file, Arrays are denoted by [ ] and dictionaries are denoted by { } .


2 Answers

json.dumps() 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

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

This is the code sample which might 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 
like image 161
Iman Mirzadeh Avatar answered Oct 08 '22 05:10

Iman Mirzadeh


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

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'])) 
like image 35
Tim Avatar answered Oct 08 '22 06:10

Tim