简体   繁体   English

Python 只获取 json 中的特定值

[英]Python only get specific value in json

I am using the google vision api on python to get text on images, the api returns this json text:我在 python 上使用谷歌视觉 api 获取图像上的文字,api 返回此 json 文字:

text_annotations {
  locale: "en"
  description: "SPEED\n"
  bounding_poly {
    vertices {
      x: 6
      y: 60
    }
    vertices {
      x: 151
      y: 60
    }
    vertices {
      x: 151
      y: 117
    }
    vertices {
      x: 6
      y: 117
    }
  }
}
text_annotations {
  description: "SPEED"
  bounding_poly {
    vertices {
      x: 6
      y: 60
    }
    vertices {
      x: 151
      y: 60
    }
    vertices {
      x: 151
      y: 117
    }
    vertices {
      x: 6
      y: 117
    }
  }
}

How do I only get the description: value?我如何只得到description:值?

I have been trying: esp = response['description']我一直在尝试: esp = response['description']

But it returns:但它返回:

Traceback (most recent call last):
  File "C:\Users\fkahd\PycharmProjects\username\ai2.py", line 27, in <module>
    resp = response['description']
TypeError: 'AnnotateImageResponse' object is not subscriptable

Full code:完整代码:

import io
import os
import json

# Imports the Google Cloud client library
from google.cloud import vision

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r"C:\Users\fkahd\OneDrive\Bureau\zefoy\vision-apixxxxxxxxxxxx.json"

# Instantiates a client
client = vision.ImageAnnotatorClient()

# The name of the image file to annotate
file_name = os.path.abspath(r"C:\Users\fkahd\OneDrive\Bureau\zefoy\captchas\captcha(22).png")

# Loads the image into memory
with io.open(file_name, 'rb') as image_file:
    content = image_file.read()

image = vision.Image(content=content)

# Performs label detection on the image file
response = client.text_detection(image=image)  # returns TextAnnotation
resp = response['description']

I got the text wanted by adding:我通过添加得到了想要的文本:

print(response.text_annotations[0].description)

thanks for your "help"感谢您的帮助”

JSON filed in python are similarly interpreted as dictionaries and you can get the value of 'description' in the similar manner. python 中的 JSON 被类似地解释为字典,您可以通过类似的方式获取 'description' 的值。 Here's what you have to do:这是你必须做的:

var_name = file_name['description']

The file_name is supposed to be the name of the opened json file. file_name应该是打开的 json 文件的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM