用Hash#fetch处理好JSON [英] Handle bad JSON gracefully with Hash#fetch

查看:146
本文介绍了用Hash#fetch处理好JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从这个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆