What's the preferred way to dump a JSON object? to_json, JSON.generate or JSON.dump?

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 (an IO-like object or an object that responds to the write method) was given, the resulting JSON is written to it.


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


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.

Tags:

Ruby

Json