如何在RubyonRails中解析json?

qzwqbdag  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(354)

我正在编写一个使用IBMWatson语音到文本api的自动化脚本。检查下面的代码(我使用了ibm的语音到文本文档)。

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的响应。

3z6pesqy

3z6pesqy1#

require 'json'

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

res = JSON.parse(json)

puts res["key"]

相关问题