首页 > 解决方案 > 如何在 Ruby on Rails 中解析 JSON?

问题描述

我正在编写一个使用 IBM Watson Speech to Text API 的自动化脚本。检查下面的代码(我使用了 IBM 的 Speech to Text 文档)。

require "ibm_watson/authenticators"
require "ibm_watson/speech_to_text_v1"
include IBMWatson

authenticator = Authenticators::IamAuthenticator.new(
  apikey: "{apikey}"
)
speech_to_text = SpeechToTextV1.new(
  authenticator: authenticator
)
speech_to_text.service_url = "{url}"

speech_to_text.configure_http_client(disable_ssl_verification: true)

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
  )
  transcript_json = JSON.pretty_generate(speech_recognition_results.result)
  puts transcript_json
end

每次我ruby test.rb在终端上运行命令时,它都会给我 JSON 格式的转录结果。

LaboteamnoMacBook-puro:GoogleDriveApiTest laboteam$ ruby test.rb
{
  "result_index": 0,
  "results": [
    {
      "final": true,
      "alternatives": [
        {
          "transcript": "several tornadoes touched down as a line of severe thunderstorms swept through Colorado on Sunday ",
          "confidence": 0.94
        }
      ],
....
}

我想要parse它,但我不知道怎么做,因为有很多子键值对。我只想获取transcript键内alternatives键的值。希望得到一些关于如何解析这个 JSON 的回应。

标签: jsonrubyparsingspeech-to-text

解决方案


require 'json'

json = '{"key":"value"}'

res = JSON.parse(json)

puts res["key"]

推荐阅读