This gem provides JSON::GenericObject for method-style access to JSON data.
Instead of drilling into nested hashes with obj["a"]["b"]["c"], you can
access attributes directly: obj.a.b.c. 🚀
This class was previously part of the json gem
and was extracted into its own gem for json 3.0.0.
gem install json-generic_objectOr add it to your Gemfile:
gem 'json-generic_object'Then require 'json/generic_object' in your application. The json (>= 2.0)
and ostruct gems are pulled in automatically as dependencies.
go = JSON::GenericObject[a: 1, b: 2]
go.a #=> 1
go.b #=> 2result = JSON('{"name":"Jane","address":{"city":"Berlin"}}',
object_class: JSON::GenericObject
)
result.name #=> "Jane"
result.address.city #=> "Berlin"to_json embeds a json_class marker in the output. Note that the json
parser (>= 3.0) no longer consumes this marker — re-parsing yields a plain
Hash unless you pass object_class::
go = JSON::GenericObject[hello: 'world']
json = go.to_json
# => '{"json_class":"JSON::GenericObject","hello":"world"}'
# Re-parse with method access:
parsed = JSON.parse(json, object_class: JSON::GenericObject)
parsed.hello #=> "world"
parsed.class #=> JSON::GenericObjectfrom_hash recursively converts hashes and arrays into a tree of
GenericObject instances:
result = JSON::GenericObject.from_hash(
foo: { bar: { baz: true }, quux: [{ foobar: true }] }
)
result.foo.bar.baz #=> true
result.foo.quux.first.foobar #=> trueThe | operator merges two objects, with the receiver's attributes
taking precedence on key conflicts:
a = JSON::GenericObject[x: 1, y: 2]
b = JSON::GenericObject[y: 99, z: 3]
merged = b | a
merged.x #=> 1
merged.y #=> 2 (a wins)
merged.z #=> 3[]— Creates a new instance from a hash of attributesjson_create(data)— Deserialization hook (deprecated: the json 3.0+ parser no longer calls this)from_hash(object)— Recursively converts a data structureload(source, proc, opts)— Parses a JSON string into a GenericObjectdump(obj, *args)— Serializes an object to a JSON stringjson_creatable?/json_creatable=— Toggle thejson_classreconstruction protocol (defaults tofalse)
to_hash— Returns the internal attribute table as a plain Hash|(other)— Merges another object into a new GenericObjectas_json— Returns the JSON-serializable representation withjson_classto_json— Serializes this object to a JSON string
The homepage of this library is located at
This software is licensed under the MIT license.