Dealing with NIL in JSON::Any in Crystal Lang

One of the challenges when developing with Crystal is that it is not as forgiving about data types as, say, Python or Ruby.

nil will keep you occupied.

The following error message:

cast from Nil to String failed, at /usr/share/crystal/src/json/any.cr:220:5:220

can be solved by:

# cast to string, THEN check if it is nil
if !(shopify_data[spid][“billing_address”][“address2”].as_s? == nil)
     name = shopify_data[spid][“billing_address”][“address2”].as_s
else
     name = “fallback_failed [taxgod]”
     tg_info << “shopify_data[spid][\”billing_address\”][\”address2\”] for ” + spid + ” is nil ”                                       
end

(The above being a snipped from my internal application taxgod, which talks to the Shopify API – which will return JSON data, and some of this JSON data might be empty / nil.)

As the case is, use as_s? to cast the JSON::Any type to a string or nil, and then check whether it is nil. If it is not nil, then you can proceed with an as_s cast (which will raise if the underlying value is nil ), and set an alternative value if it is nil.