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.
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).
JSON. parse, called with option create_additions , uses that information to create a proper Ruby object.
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 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.
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With