What is the difference between JSON.load and JSON.parse?

Asked 2 months ago, Updated 2 months ago, 2 views

Ruby's JSON module has load and parse methods for loading JSON.

They look almost the same, but are there any important differences or differences in behavior? Is there anything like, "It's better to use this in this case?" Load looks more powerful at first glance, but what did you prepare parse for?

https://docs.ruby-lang.org/ja/latest/class/JSON.html#M_LOAD

Loads and returns the given JSON format string as a Ruby object.

https://docs.ruby-lang.org/ja/latest/class/JSON.html#M_PARSE

Returns the given JSON format string by converting it into a Ruby object.

ruby

2022-09-30 13:48

1 Answers

JSON.load utilizes JSON.parse internally.And each has a different purpose.

JSON.parse is implemented for JSON strings to read it in ruby's built-in format.This behavior is basically RFC4627 compliant read behavior, depending on the documentation.(Example: NaN and Infinity are not specified in rfc, so read errors occur.Specify allow_nan:true to load this in Float::NaN and so on.)

JSON.load is designed to be a little more generic and "read ruby-like objects."Specifically, you can take IO objects as arguments as well as string, you can use proc as the second argument to make arbitrary tweaks, you can read any ruby object instead of Hash according to create_additions conventions.(In fact, create_additions is also possible with JSON.parse, but it is turned off by default.)

class Foo
  def initialize(attrs)
    @attrs=attrs
  end

  def self.json_creatable?
    true
  end

  def self.json_create(attributes)
    new(attributes.reject {|k|k=='json_class'})
  end
end

JSON.load('{"json_class": "Foo", "bar": "piyo", "hoge": "fuga"}')
# =>#<Foo:[email protected]={"bar"=>"piyo", "hoge"=>"fuga"}>

There is also a difference in security: JSON.parse is implemented to read api communications in JSON, for example, so that it is not dangerous to parse any JSON without thinking.On the other hand, JSON.load is primarily intended for serialization and de-serialization, so convenience is a priority for programmers.(I think there is a principle that data that cannot be trusted should not be de-serialized.)

Specifically, create_additions, allow_nan, max_nesting are the different options for JSON.parse and JSON.load.

Note: https://stackoverflow.com/q/17226402/3090068


2022-09-30 13:48

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.