How to Write Json in Ruby

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"
  def to_json(*a)

test = {a:}
puts test.to_json