【问题标题】:Google speech API JSON parsing in python?python中的谷歌语音API JSON解析?
【发布时间】:2018-03-22 08:11:20
【问题描述】:

我得到了google json api的响应,并将文件保存在一个json文件中,如下所示

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

我想在python 2中解析它。我试过了

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

但它会引发错误

'str' object has no attribute 'results'

后来我试过了

jsondata = json.load(json_file_path)

但它说

'str' object has no attribute 'read'

有什么帮助吗?

【问题讨论】:

    标签: python json


    【解决方案1】:

    试试这个:

    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"])
    
    • 使用json.loadsstr转换/解析为dict

    • "alternatives" 的类型为 list

    如果您的数据来自 json 文件,请先读取它

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2014-03-26
    相关资源
    最近更新 更多