从 JSON 嵌套哈希中提取特定字段 [英] Extract specific field from JSON nested hashes
问题描述
我正在考虑编写一个 Web 应用程序,该应用程序会抓取 API 并以 JSON 形式返回此信息.
I am thinking of writing a web application that crawls an API and returns this information in JSON form.
但是,我只需要一个数字,然后是当前价格(在此示例中为227").我如何在 Ruby 中访问它?我不知道从哪里开始.我从来没有处理过这样的文本.
However, I am only after one number, then current price (in this sample, "227"). How can I access that in Ruby? I have no clue where to begin. I've never dealt with text like this.
为了讨论,假设我将此输出保存到实例变量 @information
For discussion's sake, suppose I save this output into instance variable @information
{
"item": {
"icon": "http://services.runescape.com/m=itemdb_rs/4332_obj_sprite.gif?id=4798",
"icon_large": "http://services.runescape.com/m=itemdb_rs/4332_obj_big.gif?id=4798",
"id": 4798,
"type": "Ammo",
"typeIcon": "http://www.runescape.com/img/categories/Ammo",
"name": "Adamant brutal",
"description": "Blunt adamantite arrow...ouch",
"current": {
"trend": "neutral",
"price": 227
},
"today": {
"trend": "neutral",
"price": 0
},
"day30": {
"trend": "positive",
"change": "+1.0%"
},
"day90": {
"trend": "positive",
"change": "+1.0%"
},
"day180": {
"trend": "positive",
"change": "+2.0%"
},
"members": "true"
}
}
推荐答案
首先关注这个帖子把这个JSON解析成Hash在 Ruby 中解析 JSON 字符串
First follow this post to parse this JSON in to Hash Parsing a JSON string in Ruby
说解析的哈希名称是 my_hash 那么下面应该给你价格
say the parsed hash name is my_hash then the following should give you price
my_hash['item']['current']['price']
正如你所说,你想把它保存在@information
As you said you want to save it in @information
@information = my_hash['item']['current']['price']
这篇关于从 JSON 嵌套哈希中提取特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!