谷歌演讲API json解析?

时间:2018-04-18 10:35:31

标签: python json python-3.x

我已从变量

中获取谷歌演讲的结果
data = {'name': '1235433175192040985', 'metadata': {'@type': 'type.googleapis.com/google.cloud.speech.v1.LongRunningRecognizeMetadata', 'progressPercent': 100, 'startTime': '2018-04-11T12:56:58.237060Z', 'lastUpdateTime': '2018-04-11T12:57:44.944653Z'}, 'done': true, 'response': {'@type': 'type.googleapis.com/google.cloud.speech.v1.LongRunningRecognizeResponse', 'results': [{'alternatives': [{'transcript': 'hi how are you', 'confidence': 0.92438406}]}, {'alternatives': [{'transcript': 'How are you doing?', 'confidence': 0.9402676}]}]}}

json_dict = json.loads(data)

关于此,它会抛出错误

JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

对于其余的解析我写了

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"])

我做错了什么?

3 个答案:

答案 0 :(得分:0)

Python中的JSON解析器希望你的blob使用双引号,因为那是JSON standard

{
  "name": "John Doe"
}

您可以使用双引号替换单引号,如this answer中所述。

但是,我很确定问题可以在其他地方解决,因为Google API最有可能在其响应中使用有效的JSON。您如何解析Google API的响应?

答案 1 :(得分:0)

您的代码段中的问题是您将dict传递给json.loads。 json.loads将json解码为dict,因此它是多余的和错误的。 read the docs

答案 2 :(得分:0)

dict不需要任何进一步的json方法,你可以按原样使用它。

for result in data["response"]["results"]:
  if "alternatives" in result:
    alternatives = result["alternatives"][0]
    if "confidence" in alternatives:
      print(alternatives["confidence"])
    if "transcript" in alternatives:
      print(alternatives["transcript"])

产生此输出:

0.92438406
hi how are you
0.9402676
How are you doing?