gpt4 book ai didi

ruby-on-rails - 如何使用 Ruby on Rails 将 company.address.city 转换为对象

转载 作者:数据小太阳 更新时间:2023-10-29 07:29:41 25 4
gpt4 key购买 nike

我有一些参数,我正在尝试从 ie 构建一个深层嵌套的 json 对象:company.address.city company.address.state

这是我的参数:

{"business_type"=>"company", "company.address.city"=>"Gold Coast", "company.address.line1"=>"123 fake street", "company.address.state"=>"QLD", "company.name"=>"test"}

我期待这样的事情:

business_type: "company",
company{
address{
city: "Gold Coast",
line1: "123 fake street",
state: "QLD",
},
name: "test"
}

最佳答案

以方法的形式以备不时之需

h = {"business_type"=>"company", "company.address.city"=>"Gold Coast", "company.address.line1"=>"123 fake street", "company.address.state"=>"QLD", "company.name"=>"test"}

def flatten_keys(hash)
hash.each_with_object({}) do |(key,value), all|
parts = key.split('.').map!(&:to_sym)
new = parts[0...-1].inject(all) { |h, k| h[k] ||= {} }
new[parts.last] = value
end
end

flatten_keys(h)

打印出来

=> {:business_type=>"company", :company=>{:address=>{:city=>"Gold Coast", :line1=>"123 fake street", :state=>"QLD"}, :name=>"test"}}

希望对你有帮助

关于ruby-on-rails - 如何使用 Ruby on Rails 将 company.address.city 转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57131443/

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