从阵列获得率 - json

时间:2022-10-18 07:46:35

I am trying to get the rates from this website.

我想从这个网站上获得费率。

So I connect with website = Faraday.get('https://bitpay.com/api/rates')).status == 200 and then try to parse this.

所以我用website = Faraday.get('https://bitpay.com/api/rates')).status == 200连接,然后尝试解析它。

A segment of the response I get is:

我收到的一部分回复是:

 #<Faraday::Response:0x007fcf1ce25688
  @env=
  #<struct Faraday::Env
  method=:get,
  body=
  "[{\"code\":\"BTC\",\"name\":\"Bitcoin\",\"rate\":1},      {\"code\":\"USD\",\"name\":\"US Dollar\",\"rate\":586.66},{\"code\":\"EUR\",\"name\":\"Eurozone Euro\",\"rate\":528.991322},{\"code\":\"GBP\",\"name\":\"Pound Sterling\",\"rate\":449.441986},{\"code\":\"JPY\",\"name\":\"Japanese Yen\",\"rate\":59907.95922},{\"code\":\"CAD\",\"name\"

When I do a website.body I get a String class of all these values found on that website. I want to parse them though (JSON?) so that I can get each rate as a float.

当我做一个website.body时,我得到一个String类,其中列出了该网站上的所有这些值。我想解析它们(JSON?),这样我就可以将每个速率作为一个浮点数。

I tried something JSON.parse(website.body)["GBP"]["rate"].to_f but yet again it cannot work in a string.

我尝试了一些JSON.parse(website.body)[“GBP”] [“rate”]。to_f,但它再次无法在字符串中工作。

The return I get is TypeError: no implicit conversion of String into Integer

我得到的返回值是TypeError:没有将String隐式转换为Integer

I was having a similar (but not the same) format from a different rates website and this is how I was handling it. Do I need to change its format first or is there a different way around it?

我从不同的费率网站获得了类似(但不是相同)的格式,这就是我处理它的方式。我是否需要先改变其格式,还是有不同的方式?

1 个解决方案

#1


2  

You're trying to access to the parsed JSON with the key "GBP" but you have an array. It's like if you did

您正尝试使用键“GBP”访问已解析的JSON,但您有一个数组。就像你做的那样

a = [1,2,3,4,5]
a['foo']

Try out

试用

currencies = JSON.parse(website.body)
currencies.each { |currency| puts currency['rate'] }

and change it like you need

并根据需要进行更改

#1


2  

You're trying to access to the parsed JSON with the key "GBP" but you have an array. It's like if you did

您正尝试使用键“GBP”访问已解析的JSON,但您有一个数组。就像你做的那样

a = [1,2,3,4,5]
a['foo']

Try out

试用

currencies = JSON.parse(website.body)
currencies.each { |currency| puts currency['rate'] }

and change it like you need

并根据需要进行更改