Handle bad JSON gracefully with Hash # fetch

I am trying to extract some products from this JSON API so that I can display them in my views, with bad JSON gracefully handled with Hash#fetch

to declare a default value if I get null.

But why am I getting:

can't convert String into Integer

      

or if i set @json_text

in {}

:

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

      

0


source to share


1 answer


The correct way to extract is to call fetch

on the mashes variable:

mashes.fetch('products', []).each do |mash|
  puts "YOLO"
end

      



# fetch is a Hash method, in which case it is the same as mash ['product'], except when product

there is nil

, using the example fetch

will return[]

+2


source







All Articles