简体   繁体   English

Ruby String转换为格式化的JSON

[英]Ruby String to formatted JSON

I've scrapped the part of the data from the pages with Nokogiri . 我已经从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 我想将输出格式化为以下JSON格式

{
    "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? 我必须使用哪种宝石,方法来获得上述哈希或JSON格式?

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 只需在Ruby中创建等效的哈希结构,然后执行例如

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

hash.to_json

You are already including the json gem. 您已经包含了json gem。 Obviously you build the Ruby hash up in places where you currently have puts statements. 显然,您在当前具有puts语句的地方构建了Ruby哈希。

Edit: If the layout is important to you, you may prefer: 编辑:如果布局对您很重要,则您可能希望:

JSON.pretty_generate( hash )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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