【发布时间】:2013-12-31 11:08:24
【问题描述】:
首先我要说我对 Ruby 和 JSON 很陌生。
在我的模型文件中,我尝试将 JSON 解析为哈希,然后将特定的键值返回给视图。
我目前收到错误消息“没有将字符串隐式转换为整数”。我的理解是 JSON 输出返回一个哈希数组,因此我试图访问并返回第一个数组键值。
app/models/word.rb
def self.search(search)
result_json = Wordnik.word.get_definitions(search)
result_hash = JSON.parse(result_json.to_json) # Parse JSON to hash
definition = result_hash.first["text"] # return first :text key of the hash
end
Wordik.word.get_definitions 的 JSON 输出
[
{
"textProns"=>[],
"sourceDictionary"=>"ahd-legacy",
"exampleUses"=>[],
"relatedWords"=>[],
"labels"=>[],
"citations"=>[],
"word"=>"fallacy",
"text"=>"A false notion.",
"sequence"=>"0",
"score"=>0.0,
"partOfSpeech"=>"noun",
"attributionText"=>"from The American Heritage® Dictionary of the English Language, 4th Edition"
},
{
"textProns"=>[],
"sourceDictionary"=>"ahd-legacy",
"exampleUses"=>[],
"relatedWords"=>[],
"labels"=>[],
"citations"=>[],
"word"=>"fallacy",
"text"=>"A statement or an argument based on a false or invalid inference.",
"sequence"=>"1",
"score"=>0.0,
"partOfSpeech"=>"noun",
"attributionText"=>"from The American Heritage® Dictionary of the English Language, 4th Edition"
},
{
"textProns"=>[],
"sourceDictionary"=>"ahd-legacy",
"exampleUses"=>[],
"relatedWords"=>[],
"labels"=>[],
"citations"=>[],
"word"=>"fallacy",
"text"=>"Incorrectness of reasoning or belief; erroneousness.",
"sequence"=>"2",
"score"=>0.0,
"partOfSpeech"=>"noun",
"attributionText"=>"from The American Heritage® Dictionary of the English Language, 4th Edition"
},
{
"textProns"=>[],
"sourceDictionary"=>"ahd-legacy",
"exampleUses"=>[],
"relatedWords"=>[],
"labels"=>[],
"citations"=>[],
"word"=>"fallacy",
"text"=>"The quality of being deceptive.",
"sequence"=>"3",
"score"=>0.0,
"partOfSpeech"=>"noun",
"attributionText"=>"from The American Heritage® Dictionary of the English Language, 4th Edition"
}
]
我收到错误消息“没有将字符串隐式转换为整数”。
【问题讨论】:
-
将此数据复制到 IRB,并从
result_hash = JSON.parse ...开始遵循您的代码,结果我得到"A false notion."。您是否在此处省略了任何步骤? -
你上面贴的数据确实是一个哈希数组。
-
在我的模型文件中使用以下代码创建新 Word 对象时,该输出来自控制台:'def initialize(name)''self.name = name''end''def definitions' 'Wordnik.word.get_definitions(self.name)' 'end'
-
但是,Wordnik API 文档指定输出数据的默认格式是 JSON,所以我不确定在我的 self.search 方法的第一行中数据输出的格式是什么。 .
标签: ruby-on-rails ruby json