convert deeply nested JSON into OpenStruct object

This post will help you convert JSON objects into an OpenStruct object, which will allow us to extract value directly using . dot notation e.g: json_result.key

If you are using with any JSON API services, than you might have come across a situation where you have to extract certain value, check if it exists in JSON response or not and doing that in traditional way is too much pain

  "name": "John doe",
  "email": "",
  "address": {
    "primary": {
      "city": "Pokhara"

Now obviously, we want to extract a value of city but for that, we need to go with the pain of verifying each parent keys to have a child result like so:

def city(json)
  return if json['address'].blank?
  return if json['address']['primary'].blank?


=> "Pokhara"

JSON to OpenStruct object

we can simplyfy this by using Safe navigation operator and OpenStruct class.

res = JSON.parse(json, object_class: OpenStruct)
=> "Pokhara"

Hash to OpenStruct object

we can also convert hash to openstruct object by converting hash into JSON using .to_json method:

res = JSON.parse(hsh.to_json, object_class: OpenStruct)
=> "Pokhara"

More info