How to Write Json in Ruby

Fri, Sep 11, 2015

Read in 1 minutes

Just like when parsing json in ruby you need to require the json library to write hashes and arrays to json strings. Unlike Javascript and PHP you don’t call a function with one parameter representing the data you want to convert to json - instead you can call to_json on the object you want to convert.

require 'json'
data = {"name"=>"Claus Witt", "ideas"=>["idea one", "idea two"]}
puts data.to_json

For built-ins this works out of the box. For your own classes though - you need to implement a method called as_json as well as to_json. This enables your object to be directly written to json - but also lets it be nested within e.g. a hash or an array. The to_json should pretty much just call to_json on the as_json output.

require 'json'
class Test
  def as_json(options = { })
    {
      "this" => "is a test"
    }
  end
  def to_json(*a)
    as_json.to_json(*a)
  end
end

puts Test.new.to_json
test = {a: Test.new}
puts test.to_json

See Also

How to Parse Json in Ruby

Thu, Sep 10, 2015

Read more →

How to Write Json in PHP

Wed, Sep 9, 2015

Read more →

How to Read from stdin in Ruby

Fri, Aug 28, 2015

Read more →

How to Write a TCP Echo Server in Ruby

Mon, Aug 24, 2015

Read more →

How to Write Xml in Ruby

Mon, Aug 17, 2015

Read more →