Alex Craft
Alex Craft

Reputation: 15336

How to parse both Int and Float in JSON in Crystal?

Crystal JSON complains that it can't cast Int to Float, code below throws exception

JSON.parse("{\"v\":1}")["v"].as_f

How to parse it? In case when some values are Int "1" and some Floats "1.1"?

Upvotes: 0

Views: 167

Answers (1)

marzhaev
marzhaev

Reputation: 497

Crystal is comparatively strict with types here. You have to be more explicit.

Option 1.

Implement your own method. I'd recommend use a different name.

struct JSON::Any
  def to_f : Float64?
    case @raw
    when Float64 then @raw.as(Float64)
    when Int then @raw.as(Int).to_f
    end
  end
end

You can then call it as JSON.parse("{\"v\":1}")["v"].as_f

Option 2.

Inside your code do a check first.

my_v = JSON.parse("{\"v\":1}")["v"]
if my_v.as_f?
  my_v.as_f
elsif my_v.as_i?
  my_v.to_i.to_f
end

Upvotes: 1

Related Questions