简体   繁体   中英

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:

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?

I have been trying: 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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