New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
JSON parse nil error #982
Comments
That is expected, the compiler has no way of figuring out what the parser will return at runtime, everything is possible, including nil. require "json"
json = JSON.parse("{\"response\":{\"domain_data\":\"somedata\"}}")
p typeof(json) #=> (Nil | String | Int64 | Float64 | Bool | Hash(String, JSON::Type) | Array(JSON::Type)) http://play.crystal-lang.org/#/r/72n If you're sure about the structure you can cast: require "json"
json = JSON.parse("{\"response\":{\"domain_data\":\"somedata\"}}")
casted = json as Hash
p casted["response"] http://play.crystal-lang.org/#/r/72o Or better yet use json_mapping: require "json"
class DomainData
json_mapping({
domain_data: String
})
end
class Response
json_mapping({
response: DomainData
})
end
response = Response.from_json("{\"response\":{\"domain_data\":\"somedata\"}}")
p response.response.domain_data http://play.crystal-lang.org/#/r/72p If you're unsure you have to use runtime checks: require "json"
json = JSON.parse("{\"response\":{\"domain_data\":\"somedata\"}}")
if json.is_a? Hash
data = json["response"]
if data.is_a? Hash
p data["domain_data"]
end
end |
Oh and your working examples work because all elements in the union respond to the |
👍 Thanks @jhass |
Crystal 0.7.4
I am trying to parse an escaped json string.
http://play.crystal-lang.org/#/r/72m
The text was updated successfully, but these errors were encountered: