Reputation: 17928
I need to dump a hash object to JSON and I was wondering which of these three, to_json
, JSON.generate
or JSON.dump
, is the preferred way to do it.
I've tested the results of these methods and they are the same:
> {a: 1, b: 2}.to_json
=> "{\"a\":1,\"b\":2}"
> JSON.generate({a: 1, b: 2})
=> "{\"a\":1,\"b\":2}"
> JSON.dump({a: 1, b: 2})
=> "{\"a\":1,\"b\":2}"
Upvotes: 11
Views: 15532
Reputation: 7098
Working with a huge hash (300MB), to_json
was unable to generate the json string, it crashed.
However JSON.generate
did work, and so did JSON.dump
.
Upvotes: 2
Reputation: 61
For dumping arrays, hashs and objects (converted by to_hash
), these 3 ways are equivalent.
But JSON.generate
or JSON.dump
only allowed arrays, hashs and objects.
to_json
accepts many Ruby classes even though it acts only as a method for serialization, like a integer:
JSON.generate 1 # would be allowed
1.to_json # => "1"
JSON.generate
took more options for output style (like space, indent)
And JSON.dump
, output default style, but took a IO-like object as second argument to write, third argument as limit number of nested arrays or objects.
Upvotes: 3
Reputation: 198566
From docs:
JSON.generate
only allows objects or arrays to be converted to JSON syntax.to_json
, however, accepts many Ruby classes even though it acts only as a method for serialization
and
[
JSON.dumps
] is part of the implementation of the load/dump interface of Marshal and YAML.If
anIO
(anIO
-like object or an object that responds to the write method) was given, the resulting JSON is written to it.
Upvotes: 9
Reputation: 8831
JSON.generate
only allows objects or arrays to be converted to JSON syntax.
to_json
accepts many Ruby classes even though it acts only as a method for serialization
JSON.generate(1)
JSON::GeneratorError: only generation of JSON objects or arrays allowed
1.to_json
=> "1"
JSON.dump
: Dumps obj as a JSON string, calls generate on the object and returns the result.
You can get more info from here
Upvotes: 4