如何格式化正确的json输出?

时间:2018-08-20 07:00:05

标签: ruby-on-rails

这是我想要的输出:

{"USD_PHP":{"val":53.367014}}

目前,我正在对包含以下内容的单个文件进行实验:

require 'rubygems'
require 'httparty'

class RemoteGem
    include HTTParty

    base_uri "free.currencyconverterapi.com/api/v6/convert?q=USD_PHP&compact=y"

    attr_accessor :id, :val

    def initialize(val)
      self.id = id
      self.val = val

    end

    # Returns the exchange rate for this particular RemoteGem
    def versions
      response = self.class.get("/USD_PHP/#{id}.json")
      if response.success?
        response
      else
        raise response.response
      end
    end

   # Find a particular exchange rate, based on its name
    def self.find(id)
      response = get("/USDT_PHP/#{id}.json")
      if response.success?
        self.new(response["id"])
      else
        # this just raises the net/http response that was raised
        raise response.response
      end
    end
  end

httparty = RemoteGem.find("val")
puts httparty.versions

到目前为止,运行文件时,我总是得到以下输出:

    {"USD_PHP":{"id":"USD_PHP","val":53.367014,"to":"PHP","fr":"USD"}}}

如您所见,我尝试在“初始化”时对其进行格式化,我知道我的逻辑和语法是错误的。

1 个答案:

答案 0 :(得分:0)

似乎有很多代码重复。 这个版本应该可以工作:

require 'rubygems'
require 'httparty'

class RemoteGem
  include HTTParty

  base_uri "free.currencyconverterapi.com/api/v6/convert?q=USD_PHP&compact=y"

  attr_accessor :id, :val

  def initialize(val)
    self.id = id
    self.val = val
  end

    # Find a particular exchange rate, based on its name
  def self.find(id)
    self.new(id).format_output
  end

  def format_output
    output_key = 'USD_PHP'
    usd_hash = versions.fetch('results').fetch(output_key)
    {
      output_key => usd_hash.select { |k, v| k == 'val' }
    }
  end

  private

  # Returns the exchange rate for this particular RemoteGem
  def versions
    response = self.class.get("/USD_PHP/#{id}.json")
    if response.success?
      response
    else
      raise response.response
    end
  end
end

puts RemoteGem.find("val")

基本上,我在这里删除了重复项,并添加了format_output方法。 现在返回{"USD_PHP":{"val":53.367014}}

您也可以在线尝试:https://repl.it/repls/StarkSweetArray