有人给我这个哈希:
{
"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"
}
}我现在得到的价格如下:
class GpperxpController < ApplicationController
def index
end
def cooking
require 'open-uri'
@sharkid = '385'
@sharkurl = "http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=#{@sharkid}"
@sharkpage = Nokogiri::HTML(open(@sharkurl))
@sharkinfo = JSON.parse(@sharkpage.text)
@sharkinfo = @sharkinfo['item']['current']['price']
end
end在我看来,<%= @sharkinfo %>返回227。但是,我想对它执行一些数学操作,这就是我必须使用.to_i的原因。唯一的问题是当我附加.to_i时,值会改变为1,为什么呢?
发布于 2014-01-10 06:20:47
给定的json (rs/api/catalogue/detail.json?item=385)中的价格包含,。
... "current":{"trend":"neutral","price":"1,844"},...
^在调用,之前删除String#to_i。
"1,844".to_i
# => 1
"1,844".gsub(',', '').to_i
# => 1844发布于 2014-01-10 06:32:54
只要运行irb,并将您的JSON响应放入一个变量中,我就可以获得227响应,方法是将价格作为文本提取出来,然后转换为整数,或者以整数的形式一举拔出价格。
因此,我的初始代码如下:
json_text = '''
{
"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"
}
'''
require 'json'
si = JSON.parse(json_text)然后是下列任何一项:
p = si['item']['current']['price']
price = p.to_i或
price = si['item']['current']['price'].to_i把227的价值放在我的价格变量中。
不过,如果我是你的话,我会避免对不同的事物使用相同的变量名。如果您想要的是@sharkinfo中的整数价格,那么最好有一个临时名称(没有@符号)将价格作为文本放入,然后将整数值赋给所需的变量。
试试这个,看看它是否有用。我会试着监视一下这件事,看看你有没有进展。另外,从JSON中提取文本时,我相信这不再是JSON问题了。最后,您可以包括您使用的ruby版本以及使用的平台(Windows/Mac/Linux/等等)。
https://stackoverflow.com/questions/21037400
复制相似问题