Convert nested JSON object to nested OpenStructs
If you are parsing a nested JSON string such as this:
{
"vendor": {
"company_name": "Basket Clowns Inc",
"website": "www.basketthecloon.com"
}
And want to access it with dot notation, simply doing:
OpenStruct.new(JSON.parse(json_str))
will not do!
Turns out there is a cool option on JSON.parse
called object_class
:
JSON.parse(json_str, object_class: OpenStruct)
Now you can access the resulting object with dot notation all the way down:
obj.vendor.website #=> "www.basketthecloon.com"
Tweet