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

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

Leave a Comment

tech