如何将复杂的Python Dict转换为API的JSON可序列化负载?

2024-06-01 02:35:52 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我用python编写了以下命令:

{'documentType': {'documentTypeId': 'XXXXXXXXXXXXXX',
  'documentTypeName': 'XXXXXXXXXXXXXXXXXXXX',
  'documentTypeVersion': 1},
'tags': [{'boundingBoxCoOrdinates': {'x1': 440.66135,
    'y1': 894.0904,
    'x2': 468.74966,
    'y2': 917.39105},
   'digitalPdfTagDetails': {'startPage': 0,
    'endPage': 0,
    'startCharIndex': 0,
    'endCharIndex': 0},
   'editedDate': 'SOMEDATET12:47:36Z',
   'contains': True,
   'tagId': 0,
   'tagName': 'SOMETAG',
   'type': 'SOMETYPE',
   'color': '#SOMECOLOR',
   'extractedData': '',
   'editedData': '',
   'editedBy': 'SOMEPERSON'}],
'uploadedFileId': 'SOMEID',
'imageHeight': 55,
'imageWidth': 55,
'Engine': 'SOMEPROCESSINGENGINE',
'fileName': 'SOMEFILENAME.jpg'}

当我在JSON参数中使用Requests库将其传递给POST api时,我会收到

TypeError: Object of type 'float32' is not JSON serializable

我怀疑,这是因为“boundingBoxCoOrdinates”中的值是numpy.float32类型。如果我使用astype(numpy.float64)将它们转换为numpy.float64,那么它似乎工作正常

如何转换此DICT中的所有此类值,以便JSON可序列化错误不会持续存在

编辑:“标记”列表中可以有多个这样的字典


Tags: 命令numpyjsontypetagsx1float64float32
3条回答

如请求文档here中所述,您可以使用json参数让请求管理dict的编码,如下所示:

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}

r = requests.post(url, json=payload)

但是,由于您得到了该错误,您可以尝试自己对dict进行编码,并通过data参数发送它,如下所示:

import json

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}

r = requests.post(url, data=json.dumps(payload))

对于不符合标准数据类型范围的所有数据类型,都需要使用自定义编码器

自定义编码器是通过子类化json.JSONEncoder类创建的:

import json
import numpy as np

class NumpyEncoder(json.JSONEncoder):
     def default(self, obj):
         if isinstance(obj, np.float32):
             return "...an appropriate representation of the item that the recipient understands..."
         # add more cases for NumPy data types as you need them

         # all other cases get default encoding
         return json.JSONEncoder.default(self, obj)


json_str = json.dumps(your_data_structure, cls=NumpyEncoder)

您可以在json调用中使用默认参数来处理numpy数组的转换:

import numpy as np
import json

d = {"floats": np.ones(10) / np.arange(1, 11)}

def handler(x):
    if isinstance(x, np.ndarray):
        return [y.item() for y in x]
    else:
        return x

json_str = json.dumps(d, default=handler)

相关问题 更多 >