Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize Ruby object to JSON and back?

I want to serialize an object to JSON, write it to file and read it back. Now I'd expect something like in .net where you have json.net or something like that and you do:

JsonSerializer.Serialize(obj);

and be done with it. You get back the JSON string.

How do I do this in Ruby? No Rails, no ActiveRecord, no nothing. Is there a gem I can't find?

I installed the JSON gem and called:

puts JSON.generate([obj])

where obj is an object like:

class CrawlStep

  attr_accessor :id, :name, :next_step

  def initialize (id, name, next_step)
    @id = id
    @name = name
    @next_step = next_step
  end
end

obj = CrawlStep.new(1, 'step 1', CrawlStep.new(2, 'step 2', nil))

All I get back is:

["#<CrawlStep:0x00000001270d70>"]

What am I doing wrong?

like image 983
sirrocco Avatar asked Dec 31 '10 09:12

sirrocco


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 does JSON serialize return?

It returns JSON data in string format. In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it creates a JavaScriptSerializer instance and calls Deserialize() by passing JSON data.

What is difference between serialize and Stringify?

stringify() ignores functions/methods when serializing. JSON also can't encode circular references. Most other serialization formats have this limitation as well but since JSON looks like javascript syntax some people assume it can do what javascript object literals can. It can't.

What is the difference between JSON and serialization?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object). If you serialize this result it will generate a text with the structure and the record returned.


1 Answers

The easiest way is to make a to_json method and a json_create method. In your case, you can do this:

class CrawlStep
  # Insert your code here (attr_accessor and initialize)

  def self.json_create(o)
    new(*o['data'])
  end

  def to_json(*a)
    { 'json_class' => self.class.name, 'data' => [id, name, next_step] }.to_json(*a)
  end
end

Then you serialize by calling JSON.dump(obj) and unserialize with JSON.parse(obj). The data part of the hash in to_json can be anything, but I like keeping it to the parameters that new/initialize will get. If there's something else you need to save, you should put it in here and somehow parse it out and set it in json_create.

like image 158
sarahhodne Avatar answered Oct 08 '22 16:10

sarahhodne