簡體   English   中英

將字節字典轉換為 JSON

[英]Convert a bytes dictionary to 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...

我嘗試轉換的每種方式都失敗了,我知道這可能很簡單,但我不確定它是什么。

您想加載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'}}}

只要您記得提供正確的編碼,您就可以將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)

Output:

{'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'}}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM