gpt4 book ai didi

ruby - Ruby lib 的 JSON.load 和 JSON.parse 方法有什么区别?

转载 作者:IT老高 更新时间:2023-10-28 12:49:25 36 4
gpt4 key购买 nike

从 ruby​​ 文档中我可以看到 load 方法将 proc 作为 arg 而 parse 没有。还有其他区别吗?比如说,当我有一个 JSON 字符串时,我应该使用哪种方法将其转换为 Ruby 对象?

load(source, proc = nil, options = {})Load a ruby data structure from a JSON source and return it. A source can either be a string-like object, an IO-like object, or an object responding to the read method. If proc was given, it will be called with any nested Ruby object as an argument recursively in depth first order. To modify the default options pass in the optional options argument as well.This method is part of the implementation of the load/dump interface of Marshal and YAML.Also aliased as: restore

parse(source, opts = {})Parse the JSON document source into a Ruby data structure and return it.

最佳答案

JSON#parse 将 JSON 字符串解析为 Ruby 哈希。

 JSON.parse('{"name": "Some Name"}') # => {"name" => "Some Name"}

JSON#load 接受字符串或 IO(文件等)并将其转换为 Ruby 哈希/数组

JSON.load File.new("names.json")     # => Reads the JSON inside the file and results in a Ruby Object.

JSON.load '{"name": "Some Name"}' # Works just like #parse

事实上,它转换任何响应 #read 方法的对象。例如:

class A
def initialize
@a = '{"name": "Some Name"}'
end

def read
@a
end
end

JSON.load(A.new) # => {"name" => "Some Name"}

关于ruby - Ruby lib 的 JSON.load 和 JSON.parse 方法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17226402/

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