使用JSON.parse创建嵌套的OpenStruct对象似乎很容易:
JSON.parse( '{"a":{"b":0}}', object_class:OpenStruct )
#<OpenStruct a=#<OpenStruct b=0>>
是否有一种更简单的方法将其转换回json,而无需创建递归函数(如此处所示:Deep Convert OpenStruct to JSON)?
答案 0 :(得分:0)
在您的结构上调用OpenStruct#to_json应该可以做到:
[2] pry(main)> JSON.parse('{"a":{"b":0}}', object_class:OpenStruct).to_json
=> "{\"a\":{\"b\":0}}"
从普通irb OpenStruct#to_json
开始不起作用:
irb(main):003:0> require 'ostruct'
=> true
irb(main):004:0> require 'json'
=> true
irb(main):005:0> JSON.parse('{"a":{"b":0}}', object_class:OpenStruct).to_json
=> "\"#<OpenStruct a=#<OpenStruct b=0>>\""
红宝石2.5.3,导轨4.2.11.1