【问题标题】:Google Cloud Vision API. Golang . How to get API JSON谷歌云视觉 API。戈朗。如何获取 API JSON
【发布时间】:2019-04-15 00:51:04
【问题描述】:

我将 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?有可能吗?

【问题讨论】:

    标签: go google-cloud-vision


    【解决方案1】:

    您在 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

    【讨论】:

    • 谢谢。如果使用 gRPC,则无法获得 JSON 而不是 .我必须手动制作一个 JSON。
    • 是的。我用 sn-p 更新了我的答案,以便为注释响应漂亮地打印 JSON。
    猜你喜欢
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 2019-03-22
    相关资源
    最近更新 更多