Json in Ruby

Ruby provides built-in support for JSON encoding and decoding, including to and from built-in and custom data types.

require 'json'

# We'll use these two classes to demonstrate encoding and
# decoding of custom types below.
class Response1
  attr_accessor :page, :fruits

  def initialize(page, fruits)
    @page = page
    @fruits = fruits
  end
end

# Only instance variables will be encoded/decoded in JSON.
class Response2
  attr_accessor :page, :fruits

  def initialize(page, fruits)
    @page = page
    @fruits = fruits
  end

  def to_json(*args)
    { 'page' => @page, 'fruits' => @fruits }.to_json(*args)
  end

  def self.from_json(json_string)
    data = JSON.parse(json_string)
    new(data['page'], data['fruits'])
  end
end

# First we'll look at encoding basic data types to
# JSON strings. Here are some examples for atomic
# values.
puts JSON.generate(true)
puts JSON.generate(1)
puts JSON.generate(2.34)
puts JSON.generate("gopher")

# And here are some for arrays and hashes, which encode
# to JSON arrays and objects as you'd expect.
slc_d = ["apple", "peach", "pear"]
puts JSON.generate(slc_d)

map_d = { "apple" => 5, "lettuce" => 7 }
puts JSON.generate(map_d)

# The JSON module can automatically encode your
# custom data types.
res1_d = Response1.new(1, ["apple", "peach", "pear"])
puts JSON.generate(res1_d)

# You can use custom to_json method on class
# to customize the encoded JSON.
res2_d = Response2.new(1, ["apple", "peach", "pear"])
puts JSON.generate(res2_d)

# Now let's look at decoding JSON data into Ruby
# values. Here's an example for a generic data
# structure.
byt = '{"num":6.13,"strs":["a","b"]}'

# We can parse the JSON string directly into a Ruby hash.
dat = JSON.parse(byt)
puts dat

# We can access the values in the decoded hash directly.
num = dat["num"]
puts num

# Accessing nested data is straightforward in Ruby.
strs = dat["strs"]
str1 = strs[0]
puts str1

# We can also decode JSON into custom data types.
str = '{"page": 1, "fruits": ["apple", "peach"]}'
res = Response2.from_json(str)
puts res.page
puts res.fruits[0]

# In Ruby, we can use puts to directly output JSON,
# or we can use File.write to write to a file.
d = { "apple" => 5, "lettuce" => 7 }
puts JSON.generate(d)

To run the program:

$ ruby json_example.rb
true
1
2.34
"gopher"
["apple","peach","pear"]
{"apple":5,"lettuce":7}
{"page":1,"fruits":["apple","peach","pear"]}
{"page":1,"fruits":["apple","peach","pear"]}
{"num"=>6.13, "strs"=>["a", "b"]}
6.13
a
1
apple
{"apple":5,"lettuce":7}

We’ve covered the basics of JSON in Ruby here, but check out the JSON module documentation for more details.