使用Hash #fetch优雅地处理错误的JSON
我正在尝试从这个JSON API中获取一些产品,所以我可以在我的视图中显示它们,使用Hash#fetch
#fetch优雅地处理坏JSON,如果我得到nil,则声明一个默认值。
但为什么我得到:
can't convert String into Integer
或者如果我将@json_text
设置为{}
:
undefined method 'fetch' for `nil:NilClass`
直播应用: 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
获取的正确方法是通过调用mashes变量上的fetch
:
mashes.fetch('products', []).each do |mash| puts "YOLO" end
#fetch是一个Hash方法,在这种情况下与mashes [‘product’]相同,除非product
为nil
,使用fetch
示例将返回[]