Python - Convert a bytes array into JSON format
本问题已经有最佳答案,请猛点这里访问。
我想将一个字节数组转换成JSON格式,这个源代码是:
1 | 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\'}]' |
这是我想要的结果:
1 2 3 4 5 6 7 8 9 10 | [{ "Date":"2016-05-21T21:35:40Z", "CreationDate":"2012-05-05", "LogoType":"png", "Ref": 164611595, "Classes": [ "Email addresses", "Passwords" ], "Link":"http://some_link.com"}] |
谢谢你的帮助
编辑:
首先,我将字节转换为字符串:
1 | my_new_string_value = my_bytes_value.decode("utf-8") |
但当我试图加载到json:
您的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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) |
输出
1 | ["date":"2016-05-21t21:35:40z","creationdate":"2012-05-05","logotype":"png","ref":164611595,"classe":["email addresses","passwords"],"link":"http://someu link.com<div class="suo-content">[collapse title=""]<ul><li>我不相信它是一个JSON字符串,而是一个python repr,所以使用literal_eval代替</li></ul>[/collapse]</div><hr><P>要将这个字节数组直接转换为JSON,可以首先使用decode()将字节数组转换为字符串,utf-8是标准的。更改引号..最后一步是从转储的字符串中删除",将JSON对象从字符串更改为列表。</P>[cc lang="python"]dumps(s.decode()).replace("'", '"')[1:-1] |