如何把一个JSON对象,转换成树形的对象列表?通过 . 符号可以访问对象数据?
方法一:
用ActiveSupport::HashWithIndifferentAccess可以直接支持
方法二:
用OpenStructure:
require 'json'
require 'ostruct'
def json_to_obj(s)
def h2o(x)
x.is_a?(Hash) ?
OpenStruct.new(x.keys.each_with_object({}) { |e, h|
h[e] = h2o(x[e])
}) :
x
end
h2o(JSON.parse(s))
end
x = {a: 1, b: {c: {d: 2}}}.to_json
# => "{\"a\":1,\"b\":{\"c\":{\"d\":2}}}"
p json_to_obj(x).b.c.d
# => 2
方法三:
drawer.stations.tv.header
JSON string:
{
"drawer" : {
"stations" : {
"tv" : {
"header" : "TV Channels",
"logos" : {
"one" : "www1",
"two" : "www2",
"three" : "www3"
}
}
}
}
}
require 'json'
require 'hashie'
hash = JSON.parse json_string
obj = Hashie::Mash.new hash
obj.drawer.stations.tv.header