Stefanos.Ioannou Stefanos.Ioannou - 1 year ago 80
Ruby Question

Getting rates from an array - json

I am trying to get the rates from this website.

So I connect with

website = Faraday.get('')).status == 200
and then try to parse this.

A segment of the response I get is:

#<struct Faraday::Env
"[{\"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.

I tried something
but yet again it cannot work in a string.

The return I get is
TypeError: no implicit conversion of String into 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?

Answer Source

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

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

Try out

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

and change it like you need

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download