Conversión de diccionario a JSON en python


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

No puedo acceder a mis datos en el json. ¿Qué estoy haciendo mal?

TypeError: string indices must be integers, not str
Author: Tim Castelijns, 2014-11-05

3 answers

json.dumps() convierte un diccionario en objeto str, no un objeto json (dict)! así que tienes que cargar tu str en un dict para usarlo usando json.loads() método

Vea json.dumps() como un método save y json.loads() como un método retrieve.

Este es el ejemplo de código que podría ayudarle a entenderlo más:

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
 243
Author: Iman Mirzadeh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-15 09:38:26

json.dumps() devuelve la representación de cadena JSON del diccionario de python. Ver los documentos

No puedes hacer r['rating'] porque r es una cadena, ya no un dictado

Quizás quisiste decir algo como

r = {'is_claimed': 'True', 'rating': 3.5}
json = json.dumps(r) # note i gave it a different name
file.write(str(r['rating']))
 14
Author: Tim Castelijns,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-04 21:44:32

No es necesario convertirlo en una cadena usando json.dumps()

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

Puede obtener los valores directamente del objeto dict.

 -1
Author: user3273866,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-24 13:18:27