Array values to keys? - ruby-on-rails

I am parsing some XML to JSON and then serving this on http://floating-gorge-9520.herokuapp.com/currencies.
I want to display the data so the values for currency are the keys and the values for rate then become the values for the new currency data.
For example:
USD: 1
GBP: 0.5
What is the best way of doing this?

Using two currencies for simplicity:
require 'json'
a = [{"currency"=>"USD", "rate"=>"1.3707"},
{"currency"=>"JPY", "rate"=>"140.50"}]
Hash[a.map { |h| [h['currency'],h['rate'].to_f] }]
# => {"USD"=>1.3707, "JPY"=>140.5}
Just append a .to_json on the last statement to get the JSON string.

Check this out
require 'json'
a = {}
json = '[{"currency":"USD","rate":"1.3707"},{"currency":"JPY","rate":"140.50"},{"currency":"BGN","rate":"1.9558"},{"currency":"CZK","rate":"27.368"},{"currency":"DKK","rate":"7.4625"},{"currency":"GBP","rate":"0.82183"},{"currency":"HUF","rate":"311.89"},{"currency":"LTL","rate":"3.4528"},{"currency":"PLN","rate":"4.1661"},{"currency":"RON","rate":"4.5222"},{"currency":"SEK","rate":"8.9953"},{"currency":"CHF","rate":"1.2195"},{"currency":"NOK","rate":"8.3670"},{"currency":"HRK","rate":"7.6685"},{"currency":"RUB","rate":"49.0415"},{"currency":"TRY","rate":"3.0097"},{"currency":"AUD","rate":"1.5283"},{"currency":"BRL","rate":"3.2577"},{"currency":"CAD","rate":"1.5304"},{"currency":"CNY","rate":"8.3495"},{"currency":"HKD","rate":"10.6313"},{"currency":"IDR","rate":"16097.50"},{"currency":"ILS","rate":"4.8062"},{"currency":"INR","rate":"85.1580"},{"currency":"KRW","rate":"1469.53"},{"currency":"MXN","rate":"18.2348"},{"currency":"MYR","rate":"4.5158"},{"currency":"NZD","rate":"1.6558"},{"currency":"PHP","rate":"61.092"},{"currency":"SGD","rate":"1.7376"},{"currency":"THB","rate":"44.603"},{"currency":"ZAR","rate":"15.1355"}]';
JSON.parse(json).each { |x| a[x['currency']] = x['rate'] }
print a

Related

Extract Substring from String / Ruby

I get the datas from a variable called "apps".
And I have this datastructure:
{"id"=>001,
"name"=>"test01",
"users"=>
[{"id"=>01,
"name"=>"test02"},
{"id"=>02,
"name"=>"test03"}]}
How can I extract the namevalues from the users substring?
I have tried
apps.each do |test|
data = Hash.new
data['id'] = test['id']
data['name'] = test['name']
data['username'] = test['users.name']
userdata = data
userdata.each do |row|
File.write('test.yaml', row.to_yaml)
end
end
But that doesn't work.
desired output would be:
{"id"=>"01", "name"=>"test02","id"=>"02", "name"=>"test03"}
you just need to require 'yaml' in order to use it on Hash/Array classes, you don't need to iterate over array or hash, to_yaml already handles this for you.
require 'yaml'
data = {"id"=>001,
"name"=>"test01",
"users"=>
[{"id"=>01,
"name"=>"test02"},
{"id"=>02,
"name"=>"test03"}]}
File.write('test.yml', data["users"].to_yaml)

how to convert the given string to array in rails

I have the following Strings. I want them to convert into Arrays like below in rails
"[\"Winter\", \"Summer\", \"Spring\"]" to ["Winter", "Summer", "Spring"]
"[\"IELTS\", \"GRE\", \"PTE\", \"SAT\"]" to ["IELTS", "GRE", "PTE", "SAT"]
How can i convert these
You can do it with JSON.
require 'json'
string = "[\"Winter\", \"Summer\", \"Spring\"]"
JSON.parse(string)
=> ["Winter", "Summer", "Spring"]
just alternate solution (not safe) :
> string = "[\"Winter\", \"Summer\", \"Spring\"]"
> eval(string)
#=> ["Winter", "Summer", "Spring"]
Note: better option to parse with JSON

Generate a Key, Value JSON object from a Ruby Object Array

I have a Ruby array of students. Student class has attributes id, name and age.
students = [
{id:"id1",name:"name1",age:"age1"},
{id:"id2",name:"name2",age:"age2"},
{id:"id3",name:"name3",age:"age3"}
]
I want to create a JSON key value object from this array as follows.
json_object = {id1:name1, id2:name2, id3:name3}
input = [ {id:"id1",name:"name1",age:"age1"},
{id:"id2",name:"name2",age:"age2"},
{id:"id3",name:"name3",age:"age3"}]
require 'json'
JSON.dump(input.map { |hash| [hash[:id], hash[:name]] }.to_h)
#⇒ '{"id1":"name1","id2":"name2","id3":"name3"}'
Give this a go:
students = [
{id:"id1",name:"name1",age:"age1"},
{id:"id2",name:"name2",age:"age2"},
{id:"id3",name:"name3",age:"age3"}
]
json_object = students.each_with_object({}) do |hsh, returning|
returning[hsh[:id]] = hsh[:name]
end.to_json
In console:
puts json_object
=> {"id1":"name1","id2":"name2","id3":"name3"}
Your data is all identical, but if you wanted to generate a hash that took the value of students[n][:id] as keys and students[n][:name] as values you could do this:
student_ids_to_names = students.each_with_object({}) do |student, memo|
memo[student[:id]] = student[:name]
end
For your data, you'd end up with only one entry as the students are identical: { "id1" => "name1" }. If the data were different each key would be unique on :id.
Once you have a hash, you can call json_object = students_ids_to_names.to_json to get a JSON string.

Converting http_params to hash

I can obtain an array from the string
http_params="created_end_date=2013-02-28&created_start_date=2013-01-01&page_size=50&offset=0&order_id=0D1108211501118%0D%0A0D11108211501118%0D%0Ac%0D%0AD%0D%0ADK212071409743%0D%0AKK30109110100%0D%0AKK30111140300%0D%0AKK30111140400%0D%0AKK30115120100%0D%0AKK30115150100&page_number=1"
So I did myarray=http_params.split("&"):
myarray=["created_end_date=2013-02-28", "created_start_date=2013-01-01", "page_size=50", "offset=0", "order_id=0D1108211501118%0D%0A0D11108211501118%0D%0Ac%0D%0AD%0D%0ADK212071409743%0D%0AKK30109110100%0D%0AKK30111140300%0D%0AKK30111140400%0D%0AKK30115120100%0D%0AKK30115150100", "page_number=1"]
I need to convert this to a hash myhash, so that I can make a Rest Client post call for myhash.to_json. Basically it should be key,value pairs like:
{:created_end_date=>"2013-02-28",:created_start_date=>"2013-01-01"....}
I know that the inverse operation can be done like this:
http_params = myhash.map{|k,v| "#{k}=#{v}"}.join('&')
but I am unable to come up with neat code for this.
What's the best way I should go about this?
require 'cgi'
hash = CGI::parse http_params
Or you can use:
hash = Rack::Utils.parse_nested_query http_params
Which does not return the values as arrays.
With pure Ruby methods, you can convert your string into a Hash as follows:
"a=1&b=2".split('&').map { |h| Hash[*h.split("=")] }
=> [{"a"=>"1"}, {"b"=>"2"}]
A blog post how to operate on Ruby collections is here: http://thinkingonthinking.com/map-reduce-in-ruby/
To get symbols as keys, a small additional step is necessary:
"a=1&b=2".split('&').map { |h| hs = h.split("="); Hash[hs[0].to_sym, hs[1]] }
=> [{:a=>"1"}, {:b=>"2"}]
As last step, a merge of the inner Hash elements has to be done. This can be done like:
"a=1&b=2".split('&').map { |h| hs = h.split("="); Hash[hs[0].to_sym, hs[1]] }.inject({}) { |s, h| s.merge(h) }
=> {:a=>"1", :b=>"2"}

Get a particular key value from json in ruby

[
"KEY1":{"SUB_KEY1" : "VALUE1","SUB_KEY2" : "VALUE2"},
"KEY2":{"SUB_KEY1" : "VALUE1","SUB_KEY2" : "VALUE2"}
]
The above is my json object which is coming as a response.
How do I get SUB_KEY1 of KEY1 and SUB_KEY1 of KEY2 in Ruby on Rails?
Thank you.
You need to parse the JSON object into a ruby hash. Assuming your JSON response is called res:
require 'json'
obj = JSON.parse(res)
sv1 = obj['KEY1']['SUB_KEY1']
etc.
parsed_json = ActiveSupport::JSON.decode(your_json_string)
will parse your string as
[{"KEY1"=>{"SUB_KEY1"=>"VALUE1", "SUB_KEY2"=>"VALUE2"}}, {"KEY2"=>{"SUB_KEY1"=>"VALUE1", "SUB_KEY2"=>"VALUE2"}}]
You should be able to access it using something like parsed_json[1]["KEY2"]["SUB_KEY1"]
You need to parse JSON data first. Then loop over the JSON object to access the key as follow:
#response = JSON.parse(HTTParty.get(your_url).body)
#response["data"].each do |key|
puts data[0][key]
puts data[0][key2]
end

Resources