Mike Mike - 3 months ago 5x
JSON Question

What's the proper way to check if JSON has a key?

I’m using Rails 4.2.3. I have this code that is supposed to parse JSON

my_object_id = my_object.key?("id") ? my_object['id'] : nil

But when the “my_object” JSON is ‘[“name", "Info”]’, I get the below error

undefined method `key?' for ["name", "Info"]:Array

What’s the proper way check if my JSON is going to have an “id” key?


As @Pramod indicates, it seems you're confusing hashes with arrays.

You could do something like this, meaning it would only try to retrieve an id when my_object is of the correct type:

my_object_id = (my_object.is_a?(Hash) && my_object.key?("id")) ? my_object['id'] : nil

However, this need for this conditional likely indicates a weakness elsewhere in your design, since you can't be sure of the type of my_object.