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 工作,必须是自动安装的。