0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

#Ruby Json parse + object_class ( NameError: no member 'xxx' in ) ( e.g Struct )

Last updated at Posted at 2020-04-23
  • JSON paras するときの object_class の指定だと、 Struct に定義していないキーが JSON に含まれる場合に、エラーを起こしてしまうようだ ( initialize するときに余計なキーが指定されるわけだから、当たり前か )
  • object_class の指定に任せず、Struct を直接利用すれば、頑張って必要なキーだけで Struct を組み立てる事はできる
  • 他になにか良い指定ないんだろうか
require "JSON"

# OK
User = Struct.new("User", :id, :name, :email)

json_string = { id: 1, name: "Alice", email: "aaa@example.com"}.to_json

user = JSON.parse(json_string, object_class: User)
# => #<struct Struct::User id=1, name="Alice", email="aaa@example.com">


# NG
# undefined Struct key in JSON
User = Struct.new("User", :id, :name, :email)

json_string = { id: 1, name: "Alice", email: "aaa@example.com", undefined_key: "xxx"}.to_json

user = JSON.parse(json_string, object_class: User)
# NameError: no member 'undefined_key' in struct

# OK
# generate struct by yourself
User = Struct.new("User", :id, :name, :email)

json_string = { id: 1, name: "Alice", email: "aaa@example.com", undefined_key: "xxx"}.to_json

user_attributes = JSON.parse(json_string)
# => {"id"=>1, "name"=>"Alice", "email"=>"aaa@example.com", "undefined_key"=>"xxx"}

User.new(user_attributes["id"], user_attributes["name"], user_attributes["email"])
# => #<struct Struct::User id="xxx", name="zzz", email="aaa">

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?