How to convert a JSON's key to an Int32 type, so it can be accessed by that type?

#1

https://play.crystal-lang.org/#/r/6inx

require "json"


struct MonsterStruct
  JSON.mapping(
    monster_id: Int32,
    name: String
  )
end

Monsters =  Hash(String, MonsterStruct).from_json(%({"1":{"monster_id":1,"name":"Merman"}}))

puts Monsters[1].name


I like accessing my Hashes with the native type (Monsters[1]), instead of doing Monsters[monster_id.to_s]. Is this possible? If not, no big deal but just curious!

This data is exported from adminer.php (from a mysql table)

0 Likes

#2

if you really wanted, one way to do it would be using transform_keys &.to_i on your hash, which would transform each string key to an Int32. Ofc this probably isn’t the most performant.

https://play.crystal-lang.org/#/r/6iof/edit

1 Like

#3

Sweet! That works perfectly

0 Likes