What is the preferred way to reset a JSON object? to_json, JSON.generate or JSON.dump?

I need to dump the hash object in JSON, and I was wondering which of the three, to_json , JSON.generate or JSON.dump is the preferred way to do this.

I 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}" 
+6
source share
3 answers

From docs :

JSON.generate allows JSON.generate to convert objects or arrays to JSON syntax. to_json , however, accepts many Ruby classes, although it only acts as a method for serializing

and

[ JSON.dumps ] is part of the implementation of the load / dump interface of the Marshal and YAML.

If anIO was specified (an IO object or an object that corresponds to the write method), then the received JSON is written to it.

+4
source

JSON.generate allows JSON.generate to convert objects or arrays to JSON syntax.

to_json accepts many Ruby classes, although it only acts as a method for serializing

 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 an object and return a result.

You can get more information from here.

+3
source

To dump arrays, hashes, and objects (converted to_hash ), these three methods are equivalent.

But JSON.generate or JSON.dump only arrays, hashes and objects are allowed.

to_json accepts many Ruby classes, although it only acts as a method for serialization, for example an integer:

 JSON.generate 1 # would be allowed 1.to_json # => "1" 

JSON.generate took more options for the output style (e.g. space, indent)

And JSON.dump , print the default style, but take the object as the second argument for writing as the second argument, the third argument as the limit of the number of nested arrays or objects.

+2
source

All Articles