是否可以将JSON字符串转换为Ruby对象?我想用类似于:
的表达式访问其信息drawer.stations.tv.header
JSON字符串:
{
"drawer" : {
"stations" : {
"tv" : {
"header" : "TV Channels",
"logos" : {
"one" : "www1",
"two" : "www2",
"three" : "www3"
}
}
}
}
}
答案 0 :(得分:51)
您可以将字符串解析为ruby哈希,然后将其转换为Mash。 Mash为您提供类似方法的访问。
require 'json'
require 'hashie'
hash = JSON.parse json_string
obj = Hashie::Mash.new hash
obj.drawer.stations.tv.header # => "TV Channels"
你也可以在没有第三方宝石的情况下使用ruby自己的OpenStruct
:
require 'ostruct'
require 'json'
obj = JSON.parse(json_string, object_class: OpenStruct)
obj.drawer.stations.tv.header # => "TV Channels"
答案 1 :(得分:9)
如果你将这个字符串解析为ruby对象,它将返回一个ruby Hash对象,你可以像这样得到它
ruby_obj = JSON.parse(json_string)
ruby_obj['drawer']['stations']['tv']['header']
答案 2 :(得分:2)
require 'json'
json_info = %q(
{
"drawer" : {
"stations" : {
"tv" : {
"header" : "TV Channels",
"logos" : {
"one" : "www1",
"two" : "www2",
"three" : "www3"
}
}
}
}
}
)
class MyJson
def self.for(p_jason_string)
self.new(JSON.parse(p_jason_string))
end
def initialize(p_info)
@info = p_info
end
def inspect
@info.inspect
end
def method_missing(p_missing_method_name)
print 'mm '; p p_missing_method_name
key = p_missing_method_name.to_s
if @info.has_key?(key)
then
MyJson.new(@info[key])
else
puts "no key #{p_missing_method_name}"
end
end
end # class MyJson
holder = MyJson.for(json_info)
puts '-----holder.drawer'
p holder.drawer
puts '-----holder.drawer.stations'
p holder.drawer.stations
puts '-----holder.drawer.stations.tv.header'
p holder.drawer.stations.tv.header
执行:
$ ruby -v
ruby 1.9.2p320 (2012-04-20 revision 35421) [x86_64-darwin12.2.0]
$ ruby -w t.rb
-----holder.drawer
mm :drawer
{"stations"=>{"tv"=>{"header"=>"TV Channels", "logos"=>{"one"=>"www1", "two"=>"www2", "three"=>"www3"}}}}
-----holder.drawer.stations
mm :drawer
mm :stations
{"tv"=>{"header"=>"TV Channels", "logos"=>{"one"=>"www1", "two"=>"www2", "three"=>"www3"}}}
-----holder.drawer.stations.tv.header
mm :drawer
mm :stations
mm :tv
mm :header
"TV Channels"
请注意,我使用RVM并没有做任何特殊的事情让json工作,必须自动安装。