json - 如何在 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 的回应。
解决方案
require 'json'
json = '{"key":"value"}'
res = JSON.parse(json)
puts res["key"]
推荐阅读
- git - HEAD 在 sha1 处分离
- swift - GeoFire 查询后无法正确观察 Firebase
- node.js - 无法在 node.js 或 react 中访问 Gitlab env 变量
- assembly - z/OS 上的 HLASM 问题有关 Invalid OpCode 的错误
- swift - case条件表达式有多少种
- nginx - 在 Nginx 中处理来自单个域的多个应用程序
- sql - 如何获取双数据中的最后一个数据并通过查询删除另一个数据
- java - 手动删除后 IntelliJ 不删除类
- spring-boot - 如何在 RestController 之前拦截一个 RequestBody 并从另一个微服务处理一些业务规则?
- swift - SceneKit 和 ARKit 中的 simdTransform 是什么?