Google Cloud Vision API。高朗如何获取API JSON

时间:2018-11-12 10:03:34

标签: go google-cloud-vision

我将Google Cloud Vision API与Go SDK结合使用。 在某些情况下,我不想使用Golang结构读取API结果,而只想获得API调用的完整JSON响应。例如,

// detectDocumentText gets the full document text from the Vision API for an
// image at the given file path.
func detectDocumentTextURI(w io.Writer, file string) error {
        ctx := context.Background()

        client, err := vision.NewImageAnnotatorClient(ctx)
        if err != nil {
                return err
        }

        image := vision.NewImageFromURI(file)
        annotation, err := client.DetectDocumentText(ctx, image, nil)
        if err != nil {
                return err
        }

        if annotation == nil {
                fmt.Fprintln(w, "No text found.")
        } else {
                fmt.Fprintf(w, "API Response %s", ...JSON...)
        }

        return nil
}

如何从注释结构中获取JSON?有可能吗?

1 个答案:

答案 0 :(得分:2)

您要在JSON中寻找特别的东西吗?如果尝试探索返回的内容,则可以将响应对象漂亮地打印为JSON:

json, err := json.MarshalIndent(annotation, "", "  ")
if err != nil {
    log.Fatal(err)
}

fmt.Println(string(json))

从此调用中获取原始JSON响应有些困难,因为在后台它使用的是gRPC,而不是JSON。如果稍微遵循客户端代码(它是开放源代码),您最终将进入https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/vision/apiv1/image_annotator_client.go#L142

func (c *ImageAnnotatorClient) BatchAnnotateImages(ctx context.Context, req *visionpb.BatchAnnotateImagesRequest, opts ...gax.CallOption) (*visionpb.BatchAnnotateImagesResponse, error) 

您可以看到该函数建立了请求,发送了请求并返回了响应(与调用原始函数时得到的原始响应相同,仅限于res.FullTextAnnotation)。参见https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/vision/apiv1/client.go#L109