使用 Python 将 Numpy 数组发送到环聊聊天 API 的 webhook?

Sending Numpy array to a webhook for Hangouts Chat API with Python?

我在 Google Hangouts Chat 的聊天室中设置了 webhook。

我可以成功 运行 他们的示例代码,它从聊天中与 webhook 关联的机器人生成消息:

from httplib2 import Http
from json import dumps

#
# Hangouts Chat incoming webhook quickstart
#
def main():
    url = '<INCOMING-WEBHOOK-URL>'
    bot_message = {
        'text' : 'Hello World!'}

    message_headers = { 'Content-Type': 'application/json; charset=UTF-8'}

    http_obj = Http()

    response = http_obj.request(
        uri=url,
        method='POST',
        headers=message_headers,
        body=dumps(bot_message),
    )

    print(response)

if __name__ == '__main__':
    main()

但是当我尝试使用以下代码发送 Numpy 数组时:

bot_message = {
            'text' : NumpyArrayObject}

我收到错误:

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

使用 Python 列表我得到了错误:

"description": "Invalid JSON payload received. Unknown name \"text\" at \'message\': Proto field is not repeating, cannot start list."\n          }\n        ]\n      }\n    ]\n  }\n}\n')

我该怎么办?

错误的原因是NumPy数组是一个对象,估计是w/a种struct/binary/metadata,不能直接序列化(转字节流)可以保存为 JSON 格式。为此,您需要首先使用 ndarray.tolist() 之类的方法将数组转换为 可以 的内容。详情请参阅 this SO answer