← All Articles

How to Write Json in Ruby

Posted on

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 asjson as well as tojson. 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 tojson should pretty much just call tojson on the as_json output.

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

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