加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 04:24:22 所属栏目:百科 来源:网络整理
导读:我需要将一个哈希对象转储到 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.d
我需要将一个哈希对象转储到 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读