【问题标题】:JSON object must be str, bytes or bytearray, not dictJSON 对象必须是 str、bytes 或 bytearray,而不是 dict
【发布时间】:2017-07-10 06:56:53
【问题描述】:

在 Python 3 中,加载之前保存的 json,如下所示:

json.dumps(dictionary)

输出类似于

{"('Hello',)": 6, "('Hi',)": 5}

当我使用时

json.loads({"('Hello',)": 6, "('Hi',)": 5})

它不起作用,发生这种情况:

TypeError: the JSON object must be str, bytes or bytearray, not 'dict'

【问题讨论】:

  • json.loads('''{"('Hello',)": 6, "('Hi',)": 5}''')loads 中的 s 代表字符串。
  • 看起来您已经在处理实际的字典而不是字符串。您如何读取转储的数据?

标签: python json dictionary


【解决方案1】:

json.loads 将字符串作为输入并返回字典作为输出。

json.dumps 将字典作为输入并返回一个字符串作为输出。


json.loads({"('Hello',)": 6, "('Hi',)": 5})

您正在调用json.loads,并使用字典作为输入。

您可以按如下方式修复它(虽然我不太确定这样做的意义何在):

d1 = {"('Hello',)": 6, "('Hi',)": 5}
s1 = json.dumps(d1)
d2 = json.loads(s1)

【讨论】:

  • 感谢@barak manos 这真的很有帮助。我有一个返回数据是 json.loads(data) 。当我使用json.dumps(loadedData) 解码时,摆脱上述错误并设法通过object_hook 将其转换为python 对象。
【解决方案2】:
import json
data = json.load(open('/Users/laxmanjeergal/Desktop/json.json'))
jtopy=json.dumps(data) #json.dumps take a dictionary as input and returns a string as output.
dict_json=json.loads(jtopy) # json.loads take a string as input and returns a dictionary as output.
print(dict_json["shipments"])

【讨论】:

    【解决方案3】:

    您正在将字典传递给需要字符串的函数。

    这个语法:

    {"('Hello',)": 6, "('Hi',)": 5}
    

    既是一个有效的 Python 字典字面量,也是一个有效的 JSON 对象字面量。但是loads 不带字典;它接受一个字符串,然后将其解释为 JSON 并返回结果 as 一个字典(或字符串、数组或数字,取决于 JSON,但通常是字典)。

    如果您将此字符串传递给loads

    '''{"('Hello',)": 6, "('Hi',)": 5}'''
    

    然后它会返回一个看起来很像你试图传递给它的字典。

    您还可以通过执行以下操作来利用 JSON 对象文字与 Python 字典文字的相似性:

    json.loads(str({"('Hello',)": 6, "('Hi',)": 5}))
    

    但在任何一种情况下,您都只会取回您传入的字典,所以我不确定它会完成什么。你的目标是什么?

    【讨论】:

      【解决方案4】:

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

      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.loads() 用于将 JSON 数据转换为 Python 数据。

      import json
      
      # initialize different JSON data
      arrayJson = '[1, 1.5, ["normal string", 1, 1.5]]'
      objectJson = '{"a":1, "b":1.5 , "c":["normal string", 1, 1.5]}'
      
      # convert them to Python Data
      list_data = json.loads(arrayJson)
      dictionary = json.loads(objectJson)
      
      print('arrayJson to list_data :\n', list_data)
      print('\nAccessing the list data :')
      print('list_data[2:] =', list_data[2:])
      print('list_data[:1] =', list_data[:1])
      
      print('\nobjectJson to dictionary :\n', dictionary)
      print('\nAccessing the dictionary :')
      print('dictionary[\'a\'] =', dictionary['a'])
      print('dictionary[\'c\'] =', dictionary['c'])
      

      输出:

      arrayJson to list_data :
       [1, 1.5, ['normal string', 1, 1.5]]
      
      Accessing the list data :
      list_data[2:] = [['normal string', 1, 1.5]]
      list_data[:1] = [1]
      
      objectJson to dictionary :
       {'a': 1, 'b': 1.5, 'c': ['normal string', 1, 1.5]}
      
      Accessing the dictionary :
      dictionary['a'] = 1
      dictionary['c'] = ['normal string', 1, 1.5]
      
      • JSON 数据到 Python 对象的转换
      |      JSON     | Python |
      |:-------------:|:------:|
      |     object    |  dict  |
      |     array     |  list  |
      |     string    |   str  |
      |  number (int) |   int  |
      | number (real) |  float |
      |      true     |  True  |
      |     false     |  False |
      

      【讨论】:

        【解决方案5】:

        嘿,我最近在直接读取 JSON 文件时遇到了这个问题。如果有人在读取 json 文件然后解析它时遇到这个问题,就把它放在这里:

        jsonfile = open('path/to/file.json','r')
        json_data = json.load(jsonfile)
        

        请注意,我使用 load() 而不是 load()。

        【讨论】:

          猜你喜欢
          • 2019-08-27
          • 2021-06-17
          • 1970-01-01
          • 2022-12-08
          • 1970-01-01
          • 1970-01-01
          • 2021-09-09
          • 1970-01-01
          • 2021-04-19
          相关资源
          最近更新 更多