【问题标题】:TypeError: <botocore.response.StreamingBody object at 0x7f81898af438> is not JSON serializableTypeError: <botocore.response.StreamingBody object at 0x7f81898af438> is not JSON serializable
【发布时间】:2019-05-06 06:31:42
【问题描述】:

我正在尝试使用 Python 创建一个 AWS Lambda 函数,该函数应从某个 API 接收文本并返回包含 AudioStream 对象的 JSON。为此,我使用 AWS Polly。目前,我可以在我的机器上从 AWS 获取AudioStream,它工作正常。

为了使用 AWS Polly,我创建了一个特殊用户并授予他 AmazonPollyReadOnlyAccessAmazonPollyFullAccess 访问权限。

import boto3,json

polly= boto3.client('polly')
text='<speak>hey there wassup </speak>'

spoken_text=polly.synthesize_speech(Text=text,OutputFormat='mp3',VoiceId='Aditi',TextType='ssml')

newdata=json.dumps(spoken_text)
# return newdata
print(type(spoken_text))

但是当我尝试使用此代码 sn-p 以 JSON 格式返回响应时,我收到了错误。

/usr/bin/python3.5 /talker/aditi.py
Traceback (most recent call last):
  File "/talker/aditi.py", line 9, in <module>
    newdata=json.dumps(spoken_text)
  File "/usr/lib/python3.5/json/__init__.py", line 230, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python3.5/json/encoder.py", line 198, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python3.5/json/encoder.py", line 179, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <botocore.response.StreamingBody object at 0x7f81898af438> is not JSON serializable

Process finished with exit code 1

我该如何正确地做到这一点?

【问题讨论】:

标签: json amazon-web-services python-3.5 boto3 amazon-polly


【解决方案1】:

你需要使用下面的函数来传递它:

newdata=bytes(json.dumps(spoken_text))

当你想读取返回值时,你需要使用下面的方法:

print(returned_value.read())

【讨论】:

    【解决方案2】:

    在转储或返回之前先解析来自客户端的响应。

    例如:

    response = spoken_text['Body'].read().decode('utf-8')
    return response
    

    【讨论】:

      猜你喜欢
      • 2013-11-25
      • 2019-10-09
      • 2021-03-02
      • 2014-10-14
      • 1970-01-01
      • 2020-06-29
      • 2019-02-13
      • 2021-08-15
      • 1970-01-01
      相关资源
      最近更新 更多