Parse JSON Into An OpenStruct
The json
module that ships with Ruby is something I use a lot in web app APIs. When a request comes in as a string of JSON, I use JSON.parse
to turn it into a hash. That's because a hash is much easier to work with than a string representation of some JSON data.
The hash access syntax can sometimes get to be clunky. JSON.parse
is flexible enough that it can do more than turn a JSON string into a hash. It can turn it into any object that plays along. OpenStruct
is a great example of this.
To tell JSON.parse
to use a class other than Hash
, include the object_class
option.
Because of how OpenStruct
objects work, we can use method notation to access the fields parsed from the JSON string.
Last updated