Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

What's the difference between JSON.load and JSON.parse methods of Ruby lib?

From the ruby document I can see that load method takes a proc as arg while parse doesn't. Is there any other difference? Say, when I have a string of JSON, which method should I use to turn it into a Ruby object?

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.

question from:https://stackoverflow.com/questions/17226402/whats-the-difference-between-json-load-and-json-parse-methods-of-ruby-lib

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

JSON#parse parses a JSON string into a Ruby Hash.

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

JSON#load takes either a string or IO (file etc) and converts that to Ruby Hash/Array

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

In fact, it converts any object that responds to a #read method. For example:

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

  def read
    @a
  end
end

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...