【问题标题】:Sending Numpy array to a webhook for Hangouts Chat API with Python?使用 Python 将 Numpy 数组发送到用于 Hangouts Chat API 的 webhook?
【发布时间】:2018-06-16 12:26:00
【问题描述】:

我在 Google Hangouts Chat 的聊天室中设置了网络挂钩。

我可以成功运行他们的示例代码,它会从聊天中与 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')

我该怎么办?

【问题讨论】:

    标签: python hangouts-chat


    【解决方案1】:

    报错原因是NumPy数组是一个对象,大概w/各种struct/binary/metadata,不能直接序列化(转成字节流)可以保存成JSON格式。为此,您需要首先将您的数组转换为 可以 的东西,使用类似 ndarray.tolist() 的东西。详情请见this SO answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2019-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多