1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Parse JSON Into An OpenStruct as a Ruby til

This commit is contained in:
jbranchaud
2021-08-14 19:56:59 -05:00
parent c7bea5aa78
commit 45fde23db3
2 changed files with 39 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
_1143 TILs and counting..._ _1144 TILs and counting..._
--- ---
@@ -926,6 +926,7 @@ _1143 TILs and counting..._
- [Or Operator Precedence](ruby/or-operator-precedence.md) - [Or Operator Precedence](ruby/or-operator-precedence.md)
- [Override The Initial Sequence Value](ruby/override-the-initial-sequence-value.md) - [Override The Initial Sequence Value](ruby/override-the-initial-sequence-value.md)
- [Parallel Bundle Install](ruby/parallel-bundle-install.md) - [Parallel Bundle Install](ruby/parallel-bundle-install.md)
- [Parse JSON Into An OpenStruct](ruby/parse-json-into-an-open-struct.md)
- [Parsing A CSV With Quotes In The Data](ruby/parsing-a-csv-with-quotes-in-the-data.md) - [Parsing A CSV With Quotes In The Data](ruby/parsing-a-csv-with-quotes-in-the-data.md)
- [Pass A Block To Count](ruby/pass-a-block-to-count.md) - [Pass A Block To Count](ruby/pass-a-block-to-count.md)
- [Passing Arbitrary Methods As Blocks](ruby/passing-arbitrary-methods-as-blocks.md) - [Passing Arbitrary Methods As Blocks](ruby/passing-arbitrary-methods-as-blocks.md)

View File

@@ -0,0 +1,37 @@
# 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.
```ruby
> require 'json'
=> true
> data = JSON.parse('{"name": "Josh", "city": "Chicago"}')
=> {"name"=>"Josh", "city"=>"Chicago"}
> data["name"]
=> "Josh"
```
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](https://ruby-doc.org/stdlib-3.0.1/libdoc/json/rdoc/JSON.html#module-JSON-label-Parsing+Options).
```ruby
> json_str = '{"name": "Josh", "city": "Chicago"}'
=> "{\"name\": \"Josh\", \"city\": \"Chicago\"}"
> data = JSON.parse(json_str, object_class: OpenStruct)
=> #<OpenStruct name="Josh", city="Chicago">
> data.name
=> "Josh"
```
Because of how `OpenStruct` objects work, we can use method notation to access
the fields parsed from the JSON string.
[source](https://stackoverflow.com/a/48396425/535590)