我需要将一个哈希对象转储到
JSON,我想知道这三个中的哪一个,to_json,JSON.generate或JSON.dump,是首选方法.
我已经测试了这些方法的结果,它们是相同的:
> {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}"
解决方法
从
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
和
[
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.