首页 > 解决方案 > “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 可序列化的

标签: pythongoogle-cloud-platform

解决方案


此问题已在此GitHub 链接中得到解答,这可能有助于解决您的问题。

你遇到的错误是

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

以下是GitHub线程中提供的解决方案

  • Vision 库返回普通的 protobuf 对象,可以使用以下方法将其序列化为 JSON:
from google.protobuf.json_format import MessageToJson
serialized = MessageToJson(original)

推荐阅读