用Hash#fetch处理好JSON [英] Handle bad JSON gracefully with Hash#fetch
问题描述
我正在尝试从这个JSON API中获取一些产品,以便我可以在我的视图中显示它们,使用 Hash#fetch
正确处理不良的JSON声明默认值但是为什么我会得到:
不能将String转换成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:[]
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $]]]]]]]]]]]]]]]]]]]]]]]]]]]
mashes.products.fetch('products',[])。each do | mash |
putYOLO
end
end
end
正确的获取方法是通过在mashes变量上调用 fetch
:
mashes.fetch('products',[])。each do | mash |
放YOLO
结束
#fetch 是一个哈希方法,在这种情况下与mash相同['product'],除了产品
是 nil
,使用 fetch
示例将返回 []
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
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 []
这篇关于用Hash#fetch处理好JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!