Ruby-尝试使用嵌套的哈希遍历哈希(反序列化JSON对象之后)

时间:2019-10-05 16:05:03

标签: json ruby loops hash

我是Ruby的新手,我想写一个可以调用API并反序列化JSON对象的程序。

作为参考,这是我正在调用的API; https://api.exchangeratesapi.io/latest?base=GBP

我在遍历哈希时遇到麻烦,遇到以下错误:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, 
        android.R.layout.simple_list_item_1, yourList) {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        TextView text = (TextView) view.findViewById(android.R.id.text1);
        text.setTextColor(Color.WHITE);
        return view;
    }
};

这是我到目前为止的代码(带注释)

Traceback (most recent call last):
        2: from ruby-api.rb:21:in `<main>'
        1: from ruby-api.rb:21:in `each'
ruby-api.rb:23:in `block in <main>': undefined method `each' for "GBP":String (NoMethodError)

这是运行代码时的完整输出:

#requiring the library for http client
require 'net/http'
#require the URI library
require 'uri'
#requiring the json library for deserialising JSON objects
require 'json'

#output of get request stored in a string to deserialise JSON
json_string = Net::HTTP.get(URI.parse('https://api.exchangeratesapi.io/latest?base=GBP'))

#testing output
puts "Direct output \n#{json_string}"

puts "First JSON Parse attempt\n"
JSON.parse(json_string).each do |currency, rate|
    puts "#{currency} - #{rate}"
end

#parse the JSON object to a hash and iterate through it, displaying each key, value pair
puts "JSON Parse output with nested each statements \n"
JSON.parse(json_string).each do |key, value|
    #however - this contains a nested hash! So a nested each do is needed.
    value.each do |currency, rate|
        puts "#{currency} - #{rate}"
    end
end

因此,发生的事情是它会愉快地遍历哈希,但是一旦它击中“基本”键(值为GBP),它就会掉下来。

解决此问题的最佳方法是什么? 谢谢!

1 个答案:

答案 0 :(得分:2)

您正在尝试遍历解析的JSON中的每个值,该值可同时工作,因为rates的值是一个哈希值,但是base和{{1}的值}是字符串。在此处调用date并获取NoMethodError异常。

尝试改用each键:

dates