【问题标题】:Object of type bytes is not JSON serializablebytes 类型的对象不是 JSON 可序列化的
【发布时间】:2022-12-12 03:02:31
【问题描述】:

一个函数正在返回一个字典,它有字节类型的数据。因为它在里面,它给了一个字典,我不能做简单的转换,使用

value.decode('ISO-8859-1')

我需要遍历整个字典及其证明数据类型的内部数据,以便用解码覆盖它。 为了模拟,我留下了一个返回相同错误的示例代码:

import json

dictionary ={ 
  "id": "04", 
  "name": "sunil", 
  "code": b"HR"
} 
      
json_object = json.dumps(dictionary, indent = 4) 
print(json_object)

我想将字典中的这个内部字节数据转换成一些 str,这样我就可以生成 json 。

【问题讨论】:

    标签: python json dictionary byte serializable


    【解决方案1】:
    import json
    
    dictionary ={ 
      "id": "04", 
      "name": "sunil", 
      "code": b"HR".decode('UTF-8')
    } 
          
    json_object = json.dumps(dictionary, indent = 4) 
    print(type(json_object))
    

    不确定你的字典是否有错误?但如果不试试这个呢?

    【讨论】:

      【解决方案2】:

      我用这个递归函数解决了我的问题。

      def decodeDictionary(dictionary):
      if type(dictionary) == dict:
          for key in dictionary.keys():
              decodeDictionary(dictionary[key])
      elif type(dictionary[key]) == bytes:
          dictionary[key] = dictionary[key].decode('ISO-8859-1')  
      

      【讨论】:

        猜你喜欢
        • 2018-12-31
        • 2021-01-31
        • 2018-10-10
        • 2019-09-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-11
        • 2021-07-04
        • 2021-12-10
        相关资源
        最近更新 更多