From 45fde23db39c23c13223eec9e672b86f872dee68 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sat, 14 Aug 2021 19:56:59 -0500 Subject: [PATCH] Add Parse JSON Into An OpenStruct as a Ruby til --- README.md | 3 ++- ruby/parse-json-into-an-open-struct.md | 37 ++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 ruby/parse-json-into-an-open-struct.md diff --git a/README.md b/README.md index 7470d20..ff1a8b1 100644 --- a/README.md +++ b/README.md @@ -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). -_1143 TILs and counting..._ +_1144 TILs and counting..._ --- @@ -926,6 +926,7 @@ _1143 TILs and counting..._ - [Or Operator Precedence](ruby/or-operator-precedence.md) - [Override The Initial Sequence Value](ruby/override-the-initial-sequence-value.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) - [Pass A Block To Count](ruby/pass-a-block-to-count.md) - [Passing Arbitrary Methods As Blocks](ruby/passing-arbitrary-methods-as-blocks.md) diff --git a/ruby/parse-json-into-an-open-struct.md b/ruby/parse-json-into-an-open-struct.md new file mode 100644 index 0000000..56ab5ab --- /dev/null +++ b/ruby/parse-json-into-an-open-struct.md @@ -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) +=> # +> 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)