gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:43:49 24 4
gpt4 key购买 nike

我需要将哈希对象转储到 JSON,我想知道这三个中的哪一个,to_jsonJSON.generateJSON.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})
=> "{\"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 - 转储 JSON 对象的首选方法是什么? to_json、JSON.generate 还是 JSON.dump?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32756039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com