问题
I'm trying to fetch some products from this JSON API so I can display them in my views, with bad JSON gracefully handled using Hash#fetch to declare a default value if I get nil.
But why am I getting:
can't convert String into Integer
or if I set @json_text to {}:
undefined method 'fetch' for `nil:NilClass`
Live app: http://runnable.com/U-QEWAnEtDZTdI_g/gracefully-handle-bad-json
class MainController < ApplicationController
require 'hashie'
def index
@json_text = <<END
{
"products": []
}
END
hashes = JSON.parse(@json_text)
mashes = Hashie::Mash.new(hashes)
products = []
mashes.products.fetch('products', []).each do |mash|
puts "YOLO"
end
end
end
回答1:
The right way to fetch is by calling fetch on mashes variable:
mashes.fetch('products', []).each do |mash|
puts "YOLO"
end
#fetch is a Hash method and in this case is the same as mashes['product'], except when product is nil, using the fetch example will return []
来源:https://stackoverflow.com/questions/25193627/handle-bad-json-gracefully-with-hashfetch