You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python读取JSON嵌套数组中的transcript字段

如何用Python读取JSON嵌套数组中的transcript字段

嘿,我看你已经成功加载了整个JSON文件,但卡在了获取嵌套的transcript字段上对吧?别担心,咱们来一步步拆解这个问题~

首先,先理清楚你的JSON结构:

  • 最外层的results是一个数组,每个数组元素里包含了alternatives数组
  • 你要找的transcript,就藏在alternatives数组的每个对象里

你之前的代码只遍历了results数组,但没有深入到下一层的alternatives,所以才拿不到目标字段。这里给你两种解决方案:

方案一:遍历所有可能的alternatives(适合多候选结果的情况)

如果你的语音识别结果里,每个results项可能有多个候选的alternatives,可以用双层循环来遍历所有的transcript:

import json

# 用with语句打开文件更安全,会自动关闭文件
with open('C:\\Users\\Kerem\\Desktop\\YeniGoogleapi\\MugeAnliileTatliSert7Kasim.json', encoding="utf8") as f:
    data = json.load(f)

# 遍历results数组中的每一项
for result in data['results']:
    # 遍历当前result下的alternatives数组
    for alternative in result['alternatives']:
        # 提取并打印transcript
        print(alternative['transcript'])

方案二:直接取第一个候选结果(适合只有一个最优结果的情况)

通常语音识别返回的alternatives数组里,第一个元素是置信度最高的结果,这种情况下可以直接通过索引快速获取:

import json

with open('C:\\Users\\Kerem\\Desktop\\YeniGoogleapi\\MugeAnliileTatliSert7Kasim.json', encoding="utf8") as f:
    data = json.load(f)

for result in data['results']:
    # 直接取alternatives数组的第一个元素中的transcript
    transcript = result['alternatives'][0]['transcript']
    print(transcript)

备注:内容来源于stack exchange,提问作者KeremE.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 07:43:12