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

在Ruby on Rails中如何解析JSON并提取IBM Watson返回的transcript字段

Ruby解析IBM Watson语音转文字结果提取transcript字段方法

你现有代码中调用speech_to_text.recognize返回的结果已经是SDK解析好的结构化Ruby哈希对象,不需要将其转为JSON字符串后二次解析,直接按嵌套层级取值即可。

方法1:直接从SDK返回的结构化对象取值

替换你现有代码里输出JSON的部分即可,示例代码如下:

File.open("audio-file.flac") do |audio_file|
  speech_recognition_results = speech_to_text.recognize(
    audio: audio_file,
    content_type: "audio/flac",
    word_alternatives_threshold: 0.9
  )
  # 直接取结构化结果,不需要转JSON
  result_data = speech_recognition_results.result
  # 遍历所有识别分段结果
  result_data["results"].each do |segment|
    # 只取最终确认的识别结果,过滤中间未完成的结果
    next unless segment["final"]
    # 遍历当前分段的所有备选识别结果
    segment["alternatives"].each do |alternative|
      transcript = alternative["transcript"]
      confidence = alternative["confidence"]
      puts "识别文本:#{transcript}"
      puts "置信度:#{confidence}"
    end
  end
end

方法2:如果只有JSON字符串需要解析

如果你拿到的是已经生成好的JSON字符串,先调用JSON.parse将其转为Ruby哈希对象后再按上述逻辑取值即可:

require "json"
# 假设json_str是你拿到的JSON字符串
parsed_data = JSON.parse(json_str)
parsed_data["results"].each do |segment|
  next unless segment["final"]
  segment["alternatives"].each do |alt|
    puts alt["transcript"]
  end
end

注意事项

  • 长音频识别返回的results数组可能包含多个分段识别结果,不要直接写死[0]取第一个元素,用遍历方式兼容性更强
  • 新增final字段判断可以过滤未完成的临时识别结果,只保留最终确认的内容

内容的提问来源于stack exchange,提问作者Nico Nisaw

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 00:12:02