微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

原文地址:https://www.jb51.cc/ruby/268778.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐