将字节字典转换为JSON

时间:2020-04-23 15:37:49

标签: python json

我有一个从API返回的字节字典,现在我试图将其转换为JSON,但没有成功。

样本数据:

>>> endpoint_req.content
b'{\n  "ERSEndPoint" : {\n    "id" : "7c0504654",\n    "name" : "E123",\n    "description" : "",\n    "mac" : "E123",\n    "profileId" : "",\n    "staticProfileAssignment" : false,\n    "groupId" : "7fe99b20-322b-11ea-b4b9-3a35502b4b8b",\n    "staticGroupAssignment" : true,\n    "portalUser" : "",\n    "identityStore" : "",\n    "identityStoreId" : "",\n    "link" : {\n      "rel" : "self",\n      "href" : "https://",\n      "type" : "application/json"\n    }\n  }\n}'
>>> edata = json.dumps(endpoint_req.content.decode('utf-8'))
>>> edata
'"{\\n  \\"ERSEndPoint\\" : {\\n    \\"id\\" : \\"7c0504654...
>>> edata['ERSEndPoint']
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError
edata = ast.literal_eval(edata)
>>> edata['ERSEndPoint']
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: string indices must be integers
>>> edata
'{\n  "ERSEndPoint" : {\n    "id" : "7c0504654",\n...

我尝试转换的每种方法都失败了,我知道这可能很简单,但是我不确定它是什么。

2 个答案:

答案 0 :(得分:1)

您要加载loads,然后首先使用decode进行解码。

import json
edata = json.loads(endpoint_req.content.decode("utf-8"))
edata
{'ERSEndPoint': {'id': '7c0504654', 'name': 'E123', 'description': '', 'mac': 'E123', 'profileId': '', 'staticProfileAssignment': False, 'groupId': '7fe99b20-322b-11ea-b4b9-3a35502b4b8b', 'staticGroupAssignment': True, 'portalUser': '', 'identityStore': '', 'identityStoreId': '', 'link': {'rel': 'self', 'href': 'https://', 'type': 'application/json'}}}

答案 1 :(得分:1)

只要您记得提供正确的编码,就可以将bytes直接送入json.loads

import json
content = b'{\n  "ERSEndPoint" : {\n    "id" : "7c0504654",\n    "name" : "E123",\n    "description" : "",\n    "mac" : "E123",\n    "profileId" : "",\n    "staticProfileAssignment" : false,\n    "groupId" : "7fe99b20-322b-11ea-b4b9-3a35502b4b8b",\n    "staticGroupAssignment" : true,\n    "portalUser" : "",\n    "identityStore" : "",\n    "identityStoreId" : "",\n    "link" : {\n      "rel" : "self",\n      "href" : "https://",\n      "type" : "application/json"\n    }\n  }\n}'
edata = json.loads(content, encoding='utf-8')
print(edata)

输出:

{'ERSEndPoint': {'id': '7c0504654', 'name': 'E123', 'description': '', 'mac': 'E123', 'profileId': '', 'staticProfileAssignment': False, 'groupId': '7fe99b20-322b-11ea-b4b9-3a35502b4b8b', 'staticGroupAssignment': True, 'portalUser': '', 'identityStore': '', 'identityStoreId': '', 'link': {'rel': 'self', 'href': 'https://', 'type': 'application/json'}}}