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

require "json"

struct MonsterStruct
    monster_id: Int32,
    name: String

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)

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.

1 Like

Sweet! That works perfectly