2021-01-19 Ruby JSON module
JSON.#parse
require "json"
JSON.parse('[1,2,{"name":"tanaka","age":19}]')
# => [1, 2, {"name"=>"tanaka", "age"=>19}]
JSON.#generate
require "json"
JSON.generate([1, 2, { name: "tanaka", age: 19 }])
# => "[1,2,{\"name\":\"tanaka\",\"age\":19}]"
to_json, as_json
module JSON (Ruby 3.0.0 リファレンスマニュアル)
require "json"
class User
attr :id, :name
def initialize(id, name)
@id, @name = id, name
end
def self.json_create(object)
new(object['id'], object["name"])
end
def as_json(*)
{
JSON.create_id => self.class.name,
"id" => id,
"name" => name,
}
end
def to_json(*)
as_json.to_json
end
end
json = JSON.generate(User.new(1, "tanaka"))
json # => "{\"json_class\":\"User\",\"id\":1,\"name\":\"tanaka\"}"
JSON.parse(json, create_additions: true)
# => #<User:0x0000557709b269e0 @id=1, @name="tanaka">
> JSON.create_id
=> "json_class"