I am getting a JSON response from an API, that I parse with JSON.parse(). I have a loop in my code that on each iteration checks if a certain parameter in the JSON response is equal to a defined string. This is a simpler version of the JSON response I am receiving:
{
"response": [
{
"data": {
"parameter": "value"
}
},
{
"data": {
"parameter": "value2"
}
},
{
"data": {
"parameter2": "value"
}
}
]
}
As you can see only response[0] and response[1] contain parameter. response[2] has parameter2.
So if I loop through it with:
while i < responses.size
response = responses[i]
if(response.data.parameter == "value")
*do something*
end
end
I am gonna get Unhandled exception: Missing hash key: "parameter" when I get to the third iteration. Can I ignore or better, prevent the error from happening?
If you're correctly reading the data as an array of hashes of hashes, you can use
has_key?to filter out invalid responses. The following sample code works for me:and produces the following output: