gpt4 book ai didi

ruby-on-rails - 什么时候使用 Hashie::Mash?

转载 作者:数据小太阳 更新时间:2023-10-29 08:31:54 32 4
gpt4 key购买 nike

正在从这个 JSON API 获取一些产品,我想知道 -- 我真的需要 Hashie::Mash 吗?

实时应用:http://runnable.com/U-QJCIFvY2RGWL9B/pretty-json-keys

main_controller.rb:

response = prettify(JSON.parse(@json_text))
mashie = Hashie::Mash.new(response)

@products = []
mashie.products.each do |product|
product.extend Hashie::Extensions::DeepFetch

product.price = product.deep_fetch :sale_price

@products << product
end
@products

我试过这个:

response = prettify(JSON.parse(@json_text)['products'])

@products = []
response.each do |product|
product.extend Hashie::Extensions::DeepFetch

product.price = product.deep_fetch :sale_price

@products << product
end
@products

但是返回:

Hashie::Extensions::DeepFetch::UndefinedPathError in MainController#index
Could not fetch path (sale_price) at sale_price

最佳答案

你可能想做这样的事情:

mashie.products.each do |product|
product.extend Hashie::Extensions::DeepFetch

product.price = product.deep_fetch(:sale_price) { 'Not Found' }
# Returns 'Not Found' if it does not find the key sale_price. It can be anything, like nil, 0, 'Not Found'

@products << product
end

关于ruby-on-rails - 什么时候使用 Hashie::Mash?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25213847/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com