Convertir diccionario a JSON

Resuelto sheetal_158 asked hace 9 años • 6 respuestas
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
sheetal_158 avatar Nov 05 '14 04:11 sheetal_158
Aceptado

json.dumps()¡Convierte un diccionario en strun objeto, no en un json(dict)objeto! Entonces tienes que cargarlo stren un dictpara usarlo usando json.loads()el método

Véalo json.dumps()como método de guardar y json.loads()como método de recuperación.

Este es el ejemplo de código que podría ayudarle a comprenderlo mejor:

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
Iman Mirzadeh avatar Sep 28 '2015 13:09 Iman Mirzadeh

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

No puedes hacerlo r['rating']porque r es una cadena, ya no un dict

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']))
Tim avatar Nov 04 '2014 21:11 Tim

json.dumps()se utiliza para decodificar datos JSON

  • json.loadstoma una cadena como entrada y devuelve un diccionario como salida.
  • json.dumpstoma un diccionario como entrada y devuelve una cadena como salida.
import json

# initialize different data
str_data = 'normal string'
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
    'int': int_data,
    'str': str_data,
    'float': float_data,
    'list': list_data,
    'nested list': nested_list
}

# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=4))
print('Dictionary :', json.dumps(dictionary, indent=4))  # the json data will be indented

producción:

String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
    1,
    1.5,
    [
        "normal string",
        1,
        1.5
    ]
]
Dictionary : {
    "int": 1,
    "str": "normal string",
    "float": 1.5,
    "list": [
        "normal string",
        1,
        1.5
    ],
    "nested list": [
        1,
        1.5,
        [
            "normal string",
            1,
            1.5
        ]
    ]
}
  • Conversión de datos de objetos Python a JSON
|                 Python                 |  JSON  |
|:--------------------------------------:|:------:|
|                  dict                  | object |
|               list, tuple              |  array |
|                   str                  | string |
| int, float, int- & float-derived Enums | number |
|                  True                  |  true  |
|                  False                 |  false |
|                  None                  |  null  |

ACTUALIZAR

En el archivo JSON

nested_dictionary = {
    'one': nested_list,
    'two': dictionary,

}

json_dict = {'Nested Dictionary': nested_dictionary,
             'Multiple':[nested_dictionary, nested_dictionary, nested_dictionary]
            }

with open("test_nested.json", "w") as outfile:
    json.dump(json_dict, outfile, indent=4, sort_keys=False)

respuesta del gráfico

ingrese la descripción de la imagen aquí

salida entest_nested.json

{
    "Nested Dictionary": {
        "one": [
            1,
            1.5,
            [
                "normal string",
                1,
                1.5
            ]
        ],
        "two": {
            "int": 1,
            "str": "normal string",
            "float": 1.5,
            "list": [
                "normal string",
                1,
                1.5
            ],
            "nested list": [
                1,
                1.5,
                [
                    "normal string",
                    1,
                    1.5
                ]
            ]
        }
    },
    "Multiple": [
        {
            "one": [
                1,
                1.5,
                [
                    "normal string",
                    1,
                    1.5
                ]
            ],
            "two": {
                "int": 1,
                "str": "normal string",
                "float": 1.5,
                "list": [
                    "normal string",
                    1,
                    1.5
                ],
                "nested list": [
                    1,
                    1.5,
                    [
                        "normal string",
                        1,
                        1.5
                    ]
                ]
            }
        },
        {
            "one": [
                1,
                1.5,
                [
                    "normal string",
                    1,
                    1.5
                ]
            ],
            "two": {
                "int": 1,
                "str": "normal string",
                "float": 1.5,
                "list": [
                    "normal string",
                    1,
                    1.5
                ],
                "nested list": [
                    1,
                    1.5,
                    [
                        "normal string",
                        1,
                        1.5
                    ]
                ]
            }
        },
        {
            "one": [
                1,
                1.5,
                [
                    "normal string",
                    1,
                    1.5
                ]
            ],
            "two": {
                "int": 1,
                "str": "normal string",
                "float": 1.5,
                "list": [
                    "normal string",
                    1,
                    1.5
                ],
                "nested list": [
                    1,
                    1.5,
                    [
                        "normal string",
                        1,
                        1.5
                    ]
                ]
            }
        }
    ]
}

classinstancia a JSON

  • Una solución sencilla:
class Foo(object):
    def __init__(
            self,
            data_str,
            data_int,
            data_float,
            data_list,
            data_n_list,
            data_dict,
            data_n_dict):
        self.str_data = data_str
        self.int_data = data_int
        self.float_data = data_float
        self.list_data = data_list
        self.nested_list = data_n_list
        self.dictionary = data_dict
        self.nested_dictionary = data_n_dict


foo = Foo(
    str_data,
    int_data,
    float_data,
    list_data,
    nested_list,
    dictionary,
    nested_dictionary)

# Because the JSON object is a Python dictionary. 
result = json.dumps(foo.__dict__, indent=4)
# See table above.

# or with built-in function that accesses .__dict__ for you, called vars()
# result = json.dumps(vars(foo), indent=4)

print(result) # same as before
  • Aún más simple
class Bar:
    def toJSON(self):
        return json.dumps(self, default=lambda o: o.__dict__,
                          sort_keys=False, indent=4)


bar = Bar()
bar.web = "Stackoverflow"
bar.type = "Knowledge"
bar.is_the_best = True
bar.user = Bar()
bar.user.name = "Milovan"
bar.user.age = 34

print(bar.toJSON())

respuesta del gráfico

ingrese la descripción de la imagen aquí

producción:

{
    "web": "Stackoverflow",
    "type": "Knowledge",
    "is_the_best": true,
    "user": {
        "name": "Milovan",
        "age": 34
    }
}
Milovan Tomašević avatar Feb 05 '2021 21:02 Milovan Tomašević