Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Ruby object to JSON

I would like to do something like this:

require 'json'  class Person attr_accessor :fname, :lname end  p = Person.new p.fname = "Mike" p.lname = "Smith"  p.to_json 

Is it possible?

like image 743
kapso Avatar asked Jul 12 '10 05:07

kapso


People also ask

How do you serialize an object in Ruby?

The Marshal Module As Ruby is a fully object oriented programming language, it provides a way to serialize and store objects using the Marshall module in its standard library. It allows you to serialize an object to a byte stream that can be stored and deserialized in another Ruby process.

What is JSON in Ruby?

JSON (JavaScript Object Notation) is a lightweight data interchange format. Many web applications use it to send and receive data. In Ruby you can simply work with JSON. At first you have to require 'json' , then you can parse a JSON string via the JSON. parse() command.


2 Answers

Yes, you can do it with to_json.

You may need to require 'json' if you're not running Rails.

like image 59
Salil Avatar answered Sep 28 '22 14:09

Salil


To make your Ruby class JSON-friendly without touching Rails, you'd define two methods:

  • to_json, which returns a JSON object
  • as_json, which returns a hash representation of the object

When your object responds properly to both to_json and as_json, it can behave properly even when it is nested deep inside other standard classes like Array and/or Hash:

#!/usr/bin/env ruby  require 'json'  class Person      attr_accessor :fname, :lname      def as_json(options={})         {             fname: @fname,             lname: @lname         }     end      def to_json(*options)         as_json(*options).to_json(*options)     end  end  p = Person.new p.fname = "Mike" p.lname = "Smith"  # case 1 puts p.to_json                  # output: {"fname":"Mike","lname":"Smith"}  # case 2 puts [p].to_json                # output: [{"fname":"Mike","lname":"Smith"}]  # case 3 h = {:some_key => p} puts h.to_json                  # output: {"some_key":{"fname":"Mike","lname":"Smith"}}  puts JSON.pretty_generate(h)    # output                                 # {                                 #   "some_key": {                                 #     "fname": "Mike",                                 #     "lname": "Smith"                                 #   }                                 # } 

Also see "Using custom to_json method in nested objects".

like image 26
Dmitry Shevkoplyas Avatar answered Sep 28 '22 12:09

Dmitry Shevkoplyas