ruby – 转储JSON对象的首选方法是什么? to_json,JSON.generate还是JSON.dump?

前端之家收集整理的这篇文章主要介绍了ruby – 转储JSON对象的首选方法是什么? to_json,JSON.generate还是JSON.dump?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要将一个哈希对象转储到 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 (an IO-like object or an object that responds to the write method) was given,the resulting JSON is written to it.

猜你在找的Ruby相关文章