convert deeply nested JSON into OpenStruct object
I am a full-stack Ruby on Rails developer with experience in PostgreSQL, Docker, Heroku, and performance optimization. I love exploring new technology stacks and have recently developed an interest in mobile app development using Flutter. My skills in test-driven development and fixing security vulnerabilities have helped me deliver high-quality, reliable code. I am also currently learning about machine learning and its applications in real-world problem-solving. I bring a unique combination of technical expertise, creative problem-solving, and a passion for learning to any team. I am committed to delivering elegant and efficient software solutions and excited to contribute to an innovative and dynamic team that shares this vision.
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": "[email protected]",
"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?
json['address']['primary']['city']
end
city(json)
=> "Pokhara"
JSON to OpenStruct object
we can simplyfy this by using Safe navigation operator and OpenStruct class.
res = JSON.parse(json, object_class: OpenStruct)
res.address&.primary&.city
=> "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)
res.address&.primary&.city
=> "Pokhara"

