Use of JSON class in ruby
Web API building or adding dummy APIs in your application, you would have seen the necessity of
building JSON object or parsing the JSON.
And when you parse a JSON object the object keys should be a specific type ex: String, Symbol in ruby lang.
Today we will be discussing a lesser used option in JSON.parse
method JSON parse output options
# IRB commands
> require 'json'
=> true
> dummy_data =
{
foo: "foo",
bar: "bar",
koo: {
baz: "baz"
}
}
=> {:foo=>"foo", :bar=>"bar", :koo=>{:baz=>"baz"}}
# create json object
> json = JSON.dump(dummy_data)
=> "{\"foo\":\"foo\",\"bar\":\"bar\",\"koo\":{\"baz\":\"baz\"}}"
# parse json object
> data_hash = JSON.parse(json)
=> {"foo"=>"foo", "bar"=>"bar", "koo"=>{"baz"=>"baz"}}
The one thing you would have ralized in above example that our input dummy_data
has Symbol as a key but we have got String
key after JSON
parsing.
JSON.parse
method also takes optional arguments, JSON parse output options
ex: a Option symbolize_names
(boolean) specifies whether returned Hash keys should be Symbol
; defaults to false (use Strings)
# IRB commands
> require 'json'
=> true
> dummy_data =
{
foo: "foo",
bar: "bar",
koo: {
baz: "baz"
}
}
=> {:foo=>"foo", :bar=>"bar", :koo=>{:baz=>"baz"}}
# create json object
> json = JSON.dump(dummy_data)
=> "{\"foo\":\"foo\",\"bar\":\"bar\",\"koo\":{\"baz\":\"baz\"}}"
# parse json object
> data_hash = JSON.parse(json, {symbolize_names: true})
=> {:foo=>"foo", :bar=>"bar", :koo=>{:baz=>"baz"}}
The similar functionality you get in rails framework with deep_symbolize_key
> dummy_data =
{
"foo" => "foo",
"bar" => "bar",
"koo" => {
"baz" => "baz"
}
}
=> {"foo"=>"foo", "bar"=>"bar", "koo"=>{"baz"=>"baz"}}
# create json object
> json = JSON.dump(dummy_data)
=> "{\"foo\":\"foo\",\"bar\":\"bar\",\"koo\":{\"baz\":\"baz\"}}"
# parse json object
> data_hash = JSON.parse(json).deep_symbolize_keys
=> {:foo=>"foo", :bar=>"bar", :koo=>{:baz=>"baz"}}
There are a couple of things to note as
deep_symbolize_key
has dependency with rails framework and you might not be working with rails.
And also deep_symbolize_key
doesn’t work in each case for example if we have a array json object
dummy_data = [
{
"foo" => "bar",
"name" => "one",
"group" => [4, 10]
},
"section" => "v1"
]
=> [{"foo"=>"bar", "name"=>"one", "group"=>[4, 10]}, {"section"=>"v1"}]
# create json object
json = JSON.dump(dummy_data)
=> "[{\"foo\":\"bar\",\"name\":\"one\",\"group\":[4,10]},{\"section\":\"v1\"}]"
# parse json object with symbolize_names option
> data_hash = JSON.parse(json, {symbolize_names: true})
=> [{:foo=>"bar", :name=>"one", :group=>[4, 10]}, {:section=>"v1"}]
# to use rails deep_symbolize_key method we need to recursively check the typr of
# array element and perform deep_symbolize_key
JSON.parse(json, {symbolize_names: true})
is very helpful method when you have to parse
a json object and you want the keys in a specific object Symbol
or String