Wen Wen - 6 months ago 51
Ruby Question

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.

Answer

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"}
Comments