python - “RepeatedCompositeContainer”类型的对象不是 JSON 可序列化的
问题描述
使用 Google 客户端库与视觉库交互。
我有一个从图像中检测标签的功能。
谷歌视觉.py
import os
from google.cloud import vision
from google.cloud.vision import types
from google.protobuf.json_format import MessageToJson
class GoogleVision():
def detectLabels(self, uri):
client = vision.ImageAnnotatorClient()
image = types.Image()
image.source.image_uri = uri
response = client.label_detection(image=image)
labels = response.label_annotations
return labels
我有一个 api 来调用这个函数。
from flask_restful import Resource
from flask import request
from flask import json
from util.GoogleVision import GoogleVision
import os
class Vision(Resource):
def get(self):
return {"message": "API Working"}
def post(self):
googleVision = GoogleVision()
req = request.get_json()
url = req['url']
result = googleVision.detectLabels(url)
return result
但是,它不会返回以下结果和错误
TypeError:“RepeatedCompositeContainer”类型的对象不是 JSON 可序列化的
解决方案
此问题已在此GitHub 链接中得到解答,这可能有助于解决您的问题。
你遇到的错误是
TypeError: Object of type 'RepeatedCompositeContainer' is not JSON serializable
以下是GitHub线程中提供的解决方案
- Vision 库返回普通的 protobuf 对象,可以使用以下方法将其序列化为 JSON:
from google.protobuf.json_format import MessageToJson
serialized = MessageToJson(original)
- 你也可以使用protobuf3-to-dict 之类的东西去字典。
推荐阅读
- python - Erasthotenes 的递归筛选返回无
- java - 能不能给父线程抛出异常
- linux - 在 shell 脚本中使用函数时如何记录压缩的 zip 文件
- c# - 从 C# lib 将包含字符串的结构返回给 c++ 程序
- assembly - 如何将数字转换为 ASCII
- c# - 我不能使用 ajax 调用 api 但邮递员调用没问题
- tensorflow - TensorFlow Object-Detection Fine-Tuning 导致不正确的准确度值
- firebase - 当我想从 firebase 打印数据时,构建器会重复多次
- c# - 如何在 .NET Core 2.2 中为 SignalR 配置 JsonOptions?
- reactjs - 反应生产模式