Serialize Ruby object to JSON and back?
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
.
Ruby Object to JSON and back?
It looks like the Processing
class doesn't properly implement the serialization protocol of whatever JSON serialization library you are using and thus the library does the next best thing it can: use to_s
.
How to do Ruby object serialization using JSON
Use Marshal, PStore, or another Ruby solution for non-JSON objects
One might reasonably wonder why a completely reflective language like Ruby doesn't automate JSON generation and parsing of arbitrary classes.
However, unless you stick to the JSON types, there is no place to send or receive the JSON objects except to another running Ruby. And in that case, I suspect that the conventional wisdom is "forget JSON, use a native Ruby interface like the core class Marshal
.
So, if you are really sending those objects to PHP or something non-Ruby, then you should create directly JSON-supported Ruby data structures using Array and the like, and then you will have something that JSON.generate will directly deal with.
If you just need serialization it's possible you should use Marshal
or PStore
.
Update: Aha, ok, try this:
module AutoJ
def auto_j
h = {}
instance_variables.each do |e|
o = instance_variable_get e.to_sym
h[e[1..-1]] = (o.respond_to? :auto_j) ? o.auto_j : o;
end
h
end
def to_json *a
auto_j.to_json *a
end
end
If you then include AutoJ
in each of your classes, it should DTRT. In your example this results in
{
"a": {
"string_field1": "aa",
"string_field2": "bb"
},
"b": {
"int_field3": 123,
"string_field4": "dd"
}
}
You might want to change the auto_j
method to return h.values
instead of just h
, in which case you get:
[
["aa", "bb"],
[123, "dd"]
]
How to serialize/deserialize ruby hashes/structs with objects as keys to json
JSON only allows strings as object keys. For this reason to_s is called for all keys.
You'll have the following options to solve your issue:
The best option is changing the data structure so it can properly be serialized to JSON.
You'll have to handle the stringified key yourself. An Hash produces a perfectly valid Ruby syntax when converted to a string that can be converted using Kernel#eval like Andrey Deineko suggested in the comments.
result = json.transform_keys { |key| eval(key) }
# json.transform_keys(&method(:eval)) is the same as the above.The Hash#transform_keys method is relatively new (available since Ruby 2.5.0) and might currently not be in you development environment. You can replace this with a simple Enumerable#map if needed.
result = json.map { |k, v| [eval(k), v] }.to_h
Note: If the incoming JSON contains any user generated content I highly sugest you stay away from using eval since you might allow the user to execute code on your server.
Related Topics
How to Generate a Wsdl Using Ruby
Sidekiq Worker Not Getting Triggered
Converting String "2½" (Two and a Half) into 2.5
Telling Bundler to Exclude Certain Gems from a Particular Gem's Installation
Is This the Best Way to Grab Common Elements from a Hash of Arrays
Generate Array of Numbers That Fit to a Probability Distribution in Ruby
How to Make Ruby's Restclient Gem Respect Content_Type on Post
Why Would You Use a !! Operator
Which Ruby Classes Support .Clone
How to Override Gemfile for Local Development
Rails - How to Check for Online Users
How to Fix a Slow Implicit Query on Pg_Attribute Table in Rails
Strong Parameters Not Accepting Array
Execjs::Programerror in Welcome#Index Typeerror: Object Doesn't Support This Property or Method
Could Not Find Rake-10.1.0 in Any of the Sources