Ruby 动态检查JSON中的字段是否为nil,而不使用eval
以下是我正在使用的代码摘录:Ruby 动态检查JSON中的字段是否为nil,而不使用eval,ruby,json,eval,Ruby,Json,Eval,以下是我正在使用的代码摘录: def retrieve(user_token, quote_id, check="quotes") end_time = Time.now + 15 match = false until Time.now > end_time || match @response = http_request.get(quote_get_url(quote_id, user_token)) eval("match = !JSON.parse(@
def retrieve(user_token, quote_id, check="quotes")
end_time = Time.now + 15
match = false
until Time.now > end_time || match
@response = http_request.get(quote_get_url(quote_id, user_token))
eval("match = !JSON.parse(@response.body)#{field(check)}.nil?")
end
match.eql?(false) ? nil : @response
end
private
def field (check)
hash = {"quotes" => '["quotes"][0]',
"transaction-items" => '["quotes"][0]["links"]["transactionItems"]'
}
hash[check]
end
我被告知以这种方式使用eval不是好的做法。有谁能提出一种更好的动态检查JSON节点字段存在性的方法吗?。我希望这样做:
psudo: match = !JSON.parse(@response.body) + dynamic-path + .nil?
将路径存储为路径元素数组['quotes',0]。有了一个小助手功能,你就可以避免eval了。事实上,这在这里是完全不合适的 大致如下:
class Hash
def deep_get(path)
path.reduce(self) do |memo, path_element|
return unless memo
memo[path_element]
end
end
end
path = ['quotes', 0]
hash = JSON.parse(response.body)
match = !hash.deep_get(path).nil?