Reputation: 93
Could someone advise me how to correctly parse a JSON response and convert it into a hash, please?
I would also like to extract a specific key-value pair.
The following is my JSON response.
{
"rates""=>"{
"CAD"=>1.266485552,
"HKD"=>7.7526138141,
"DKK"=>6.1233226311,
"HUF"=>294.047913065,
"PLN"=>3.702560303
},
"base""=>""USD",
"date""=>""2021-02-11"
}
Furthermore, I have the following method that can parse that JSON response. However, I would like to extract a specific key-value from 'rates' where the currency variable is my key.
def weather_url
@weather = "#{API_URL}latest?base=USD"
end
def specific_currency(currency)
@response_body ||= RestClient.get(@weather).body
@hash_response = {}
@hash_response = JSON.parse(@response_body).to_hash.assoc(currency)
end
Upvotes: 0
Views: 1448
Reputation: 151
You can use select to extract the expected key and value. Please refer ruby select.
def specific_currency(currency)
@response_body ||= RestClient.get(@weather).body
@hash_response = JSON.parse(@response_body)['rates'].select { |element| element.to_s == currency }
end
Upvotes: 3
Reputation: 28305
I'll assume that your stating point is actually valid JSON, although what you've written above is not valid JSON...
First, there is no need to write this line:
@hash_response = {}
You're assigning the variable to a meaningless value, then immediately reassigning it to the real value.
There is also no need to call to_hash
on the object, You've already got a hash.
I'm not entirely clear what you mean by "extract specific key and value", because you didn't say what you expect that method to return, but probably all you need to do is this:
def specific_currency(currency)
@response_body ||= RestClient.get(@weather).body
JSON.parse(@response_body)['rates'][currency]
end
Or if you prefer,
JSON.parse(@response_body).dig('rates', currency)
Upvotes: 3