3
我將一些XML解析爲JSON,然後在http://floating-gorge-9520.herokuapp.com/currencies上提供此服務。數組鍵值?
我想要顯示數據,以便currency
的值是關鍵字,然後rate
的值將成爲新貨幣數據的值。
例如:
USD: 1
GBP: 0.5
什麼是這樣做的最佳方式?
我將一些XML解析爲JSON,然後在http://floating-gorge-9520.herokuapp.com/currencies上提供此服務。數組鍵值?
我想要顯示數據,以便currency
的值是關鍵字,然後rate
的值將成爲新貨幣數據的值。
例如:
USD: 1
GBP: 0.5
什麼是這樣做的最佳方式?
使用爲簡單起見,兩種貨幣:
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}
上的最後一條語句只是附加一個.to_json
得到JSON字符串。
檢查this出
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
這只是輸出和以前一樣? – joshuahornby10
固定。檢查相同的鏈接。 – vooD