Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have gotten the response of google json api and saved the file in a json file which looks like this

JSON file drive.google.com/open?id=1Esuv9KpikqhwccL-dGm-IFfI5S6V7plV

And I want to parse it in python 2. I've tried

for result in response.results:
        # The first alternative is the most likely one for this portion.
        print('Transcript: {}'.format(result.alternatives[0].transcript))
        print('Confidence: {}'.format(result.alternatives[0].confidence))

but it throws the error

'str' object has no attribute 'results'

later I tried

jsondata = json.load(json_file_path)

but it says

'str' object has no attribute 'read'

Any help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
181 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try this:

data = "your json data" # of type `str`
json_dict = json.loads(data)

for result in json_dict["response"]["results"]:
  if "alternatives" in result:
    alternatives = result["alternatives"][0]
    if "confidence" in alternatives:
      print(alternatives["confidence"])
    if "transcript" in alternatives:
      print(alternatives["transcript"])
  • Use json.loads to convert / parse str to dict

  • "alternatives" is of type list

If your data is coming from a json file, read it first

with open('data.json', 'r') as f:
    data = f.read()
    # refer to above code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...