您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python-将字节数组转换为JSON格式

Python-将字节数组转换为JSON格式

您的bytes对象 几乎 是JSON,但是它使用单引号而不是双引号,并且它必须是字符串。因此,解决该问题的一种方法是解码bytestostr并替换引号。另一种选择是使用ast.literal_eval; 有关详情,请参见下文。如果要打印结果或将其作为有效JSON保存到文件中,则可以将JSON加载到python列表中,然后将其转储出去。例如,

import json

my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'logoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'

# Decode UTF-8 bytes to Unicode, and convert single quotes 
# to double quotes to make it valid JSON
my_json = my_bytes_value.decode('utf8').replace("'", '"')
print(my_json)
print('- ' * 20)

# Load the JSON to a Python list & dump it back out as formatted JSON
data = json.loads(my_json)
s = json.dumps(data, indent=4, sort_keys=True)
print(s)

[{"Date": "2016-05-21T21:35:40Z", "CreationDate": "2012-05-05", "logoType": "png", "Ref": 164611595, "Classe": ["Email addresses", "Passwords"],"Link":"http://some_link.com"}]
- - - - - - - - - - - - - - - - - - - - 
[
    {
        "Classe": [
            "Email addresses",
            "Passwords"
        ],
        "CreationDate": "2012-05-05",
        "Date": "2016-05-21T21:35:40Z",
        "Link": "http://some_link.com",
        "logoType": "png",
        "Ref": 164611595
    }
]

正如Antti Haapala在评论中提到的那样,一旦我们将其解码为字符串,就可以ast.literal_eval用来转换my_bytes_valuepython列表

from ast import literal_eval
import json

my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'logoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'

data = literal_eval(my_bytes_value.decode('utf8'))
print(data)
print('- ' * 20)

s = json.dumps(data, indent=4, sort_keys=True)
print(s)

通常,出现此问题是因为有人通过打印Pythonrepr而不是使用json模块创建正确的JSON数据来保存数据。如果可能的话,最好解决该问题,以便首先创建正确的JSON数据。

python 2022/1/1 18:15:15 有717人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶