【问题标题】:JSON with Bytes : TypeError: 'abc' has type <class 'str'>, but expected one of: (<class 'bytes'>,)JSON with Bytes : TypeError: 'abc' 的类型为 <class 'str'>,但预期为以下之一:(<class 'bytes'>,)
【发布时间】:2020-10-19 04:32:42
【问题描述】:

我在 JSON 正文中有字节作为数据输入。我不知道如何在 JSON 中格式化,所以 API 会接受它。部分 API 函数会将输入的字节通过 base64 进行序列化,以便 TensorFlow 模型可以返回预测,也就是 API 的输出。

TypeError: 'abc' 的类型为 ,但应为以下之一:(,)

解析体

{
    "cc": "b'abc'",
    "pt": "b'def'",
    "project": "xxx",
    "model": "xxx",
    "signature": "xxx",
    "version": "xxx"
}

输入的字节是通过下面的函数通过Base64序列化,以便tensorflow返回预测。

def get_serialized_example(raw):
    return tf.train.Example(
        features=tf.train.Features(
            feature={"value":
                         tf.train.Feature(bytes_list=tf.train.BytesList(value=[raw]))
                     }
        )
    ).SerializeToString()

b64_country_code = base64.b64encode(get_serialized_example(request.country_code)).decode('utf-8')
b64_project_type = base64.b64encode(get_serialized_example(request.project_type)).decode('utf-8')

【问题讨论】:

  • 我们需要比这更多的信息。请参阅How to Askhelp center
  • 我已经更新了我的帖子/。 @AMC

标签: python json api rest postman


【解决方案1】:

您的 JSON 内容似乎存在语法问题。它的格式应该是这样的:

{
"cc": "b'abc'",
"pt": "b'def'",
“项目”:“xxx”,
“型号”:“xxx”,
“签名”:“xxx”,
“版本”:“xxx”
}

在线上有大量强大的工具可以帮助处理 JSON 语法...查看Free JSON Formatter

另外,如果您还没有,请查看Postman。这是一个令人难以置信的 API 工具。您可以手动插入所有相关数据,然后将其导出为 Python 脚本……非常棒!

【讨论】:

  • 您好 ZenDiagram!谢谢你的评论!我已经相应地更改了格式,但是,对于 cc 和 pt,它们需要是字节类型。因此,b'abc',因为它返回 TypeError:“b'abc'” 具有类型 ,但预期的类型之一:(,)
  • 我还在帖子中添加了更多信息。序列化数据输入以使模型返回预测的函数。
  • TypeError: 'abc' 的类型为 ,但应为以下类型之一:(,)
  • 明白了,好的。抱歉,根据最初的帖子,问题似乎与 JSON 语法有关。看起来需要更熟悉 TensorFlow 的人来提供帮助。
【解决方案2】:

经过几天的试验,JSON 格式不会采用字节类,因此我需要将字符串作为数据输入的转换作为函数的一部分传递给字节。

 bytes_country_code = bytes(request.country_code, 'utf-8')
 bytes_project_type = bytes(request.project_type, 'utf-8')
 b64_country_code = base64.b64encode(get_serialized_example(bytes_country_code)).decode('ascii')
 b64_project_type = base64.b64encode(get_serialized_example(bytes_project_type)).decode('ascii')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-21
    • 2019-11-15
    • 2017-01-19
    • 2014-03-08
    • 2018-12-31
    • 1970-01-01
    • 2020-02-09
    • 2022-01-17
    相关资源
    最近更新 更多