Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

ruby

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.

like image 788
Wen Avatar asked Jun 21 '13 01:06

Wen


People also ask

What is the difference between JSON parse and JSON ()?

The difference is: json() is asynchronous and returns a Promise object that resolves to a JavaScript object. JSON. parse() is synchronous can parse a string to (a) JavaScript object(s).

What does JSON parse do in Ruby?

JSON. parse, called with option create_additions , uses that information to create a proper Ruby object.

Is JSON parse safe Ruby?

There are no security concerns possible. JSON isn't code, you can't inject harmful values into it. JSON. parse is safe.

How does JSON parser work?

How Does JSON Parse Work? The JSON parse function takes data that's in a text format and then converts it into JavaScript. Usually, these take the form of JavaScript objects, but the parse function can be used directly on arrays as well.


1 Answers

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"} 
like image 93
Kashyap Avatar answered Sep 21 '22 18:09

Kashyap