Wen Wen - 2 years ago 183
Ruby Question

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

From the ruby document I can see that

method takes a proc as arg while
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 Source

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

  def read

JSON.load(A.new)                      # => {"name" => "Some Name"}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download