简体   繁体   中英

Ruby String to formatted JSON

I've scrapped the part of the data from the pages with Nokogiri .

require 'net/http'
require 'nokogiri'
require 'open-uri'
require 'json'

sources = {
   cb: "http://www.cbbankmm.com/fxratesho.php",
}

puts "Currencies from CB Bank are"
if @page = Nokogiri::HTML(open(sources[:cb]))
    (1..3).each do |i|
        puts @page.css("tr")[i].text.gsub(/\s+/,'')
    end
end

The result is

Currencies from CB Bank are
USD873883
SGD706715
EURO11241135

I would like to format the output to the below JSON format

{
    "bank":"CB",
    "rates": {
        "USD":"[873,883]",
        "SGD":"[706,715]",
        "EURO":"[1124,1135]"
    }
}

Which gems, method do I have to use to get the above Hash or JSON format?

Some abstraction might be an idea. So, perhaps a class to help you with the job:

class Currencies

  def initialize(page, bank)
    @page = page
    @bank = bank
  end

  def parsed
    @parsed ||= @page.css("tr").collect{ |el| el.text.gsub(/\s+/,'') }
  end


  def to_hash
    {
      bank: @bank,
      rates: {
        USD: usd,
        SGD: sgd,
        .... 
      }
    }
  end

  def usd
    parsed[0].gsub(/^USD/, '')
  end

  def sgd
    parsed[1].gsub(/^SGD/, '')
  end

  ...

end

Use it like this

Currencies.new(Nokogiri::HTML(open(sources[:cb])), "CB").to_hash.to_json

Just make an equivalent hash structure in Ruby, and do eg

hash = {
    "bank" => "CB",
    "rates" => {
        "USD" => "[873,883]",
        "SGD" => "[706,715]",
        "EURO" => "[1124,1135]"
    }
}

hash.to_json

You are already including the json gem. Obviously you build the Ruby hash up in places where you currently have puts statements.

Edit: If the layout is important to you, you may prefer:

JSON.pretty_generate( hash )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM