【问题标题】:Converting dictionary to JSON将字典转换为 JSON
【发布时间】:2014-12-31 22:55:55
【问题描述】:
r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
file.write(str(r['rating']))

我无法访问 JSON 中的数据。我做错了什么?

TypeError: string indices must be integers, not str

【问题讨论】:

标签: python json python-2.7 dictionary


【解决方案1】:

json.dumps() 返回 python dict 的 JSON 字符串表示。 See the docs

你不能这样做 r['rating'] 因为 r 是一个字符串,而不是一个字典

也许你的意思是这样的

r = {'is_claimed': 'True', 'rating': 3.5}
json = json.dumps(r) # note i gave it a different name
file.write(str(r['rating']))

【讨论】:

    【解决方案2】:

    无需使用json.dumps()将其转换为字符串

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

    您可以直接从 dict 对象中获取值。

    【讨论】:

      【解决方案3】:

      json.dumps() 将字典转换为 str 对象,而不是 json(dict) 对象!所以你必须将你的str 加载到dict 中才能通过json.loads() 方法使用它

      json.dumps() 视为保存方法,将json.loads() 视为检索方法。

      这是可以帮助您进一步理解它的代码示例:

      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
      

      【讨论】:

      • 考虑到您已经在r 中拥有它,您不认为将json 加载回一个单独的变量loaded_r 有点低效吗?
      • 嗨!我意识到这是一个非常古老的答案,但我希望你能澄清一件事。 @TimCastelijns 提到将json加载回新变量loaded_r效率低下。这样做的有效方法是只声明 r = json.loads(r) 吗?
      • @SchrodingersStat 嗨。我不认为这会改变性能。您可以使用“timeit”功能进行检查。如果你真的想要一个快速的 json 加载/转储,你可以使用 'ujson' 库!
      • 我怀疑@TimCastelijns 误解了伊姆兰的意图。 JSON 被加载到一个新变量中并不是因为它是新信息,而是为了表明新字典中的值,即在 JSON 编码和解码往返之后,是相同的。
      【解决方案4】:

      将 r 定义为字典应该可以解决问题:

      >>> r: dict = {'is_claimed': 'True', 'rating': 3.5}
      >>> print(r['rating'])
      3.5
      >>> type(r)
      <class 'dict'>
      

      【讨论】:

        【解决方案5】:

        json.dumps()用于解码JSON数据

        • json.loads 将字符串作为输入并返回字典作为输出。
        • json.dumps 将字典作为输入并返回一个字符串作为输出。
        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
        

        输出:

        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
                ]
            ]
        }
        
        • Python 对象到 JSON 数据的转换
        |                 Python                 |  JSON  |
        |:--------------------------------------:|:------:|
        |                  dict                  | object |
        |               list, tuple              |  array |
        |                   str                  | string |
        | int, float, int- & float-derived Enums | number |
        |                  True                  |  true  |
        |                  False                 |  false |
        |                  None                  |  null  |
        

        更新

        在 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)
        
        

        图表响应

        输出到test_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
                            ]
                        ]
                    }
                }
            ]
        }
        

        class 实例转 JSON

        • 一个简单的解决方案:
        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
        
        • 更简单
        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())
        

        图表响应

        输出:

        {
            "web": "Stackoverflow",
            "type": "Knowledge",
            "is_the_best": true,
            "user": {
                "name": "Milovan",
                "age": 34
            }
        }
        

        【讨论】:

          【解决方案6】:

          您可以在上面的示例中通过在默认字典中声明一个新字典来创建一个嵌套字典。

          import json 
          dictionary = {
          'fruit':{"Grapes": "10","color": "green"},
          'vegetable':{"chilli": "4","color": "red"},
          }
          result = json.dumps(dictionary, indent = 3)
          

          打印(结果)

          这里,我使用了 indent=3

          参考:https://favtutor.com/blogs/dict-to-json-python

          【讨论】:

            猜你喜欢
            • 2018-07-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-01-29
            • 1970-01-01
            • 1970-01-01
            • 2018-03-18
            相关资源
            最近更新 更多