Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ruby – ignore empty JSON response?

Imagine I’ve the following JSON responses:

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

And sometimes I get this as well:

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "0"
        }
    }
}

Now, I want to access the upper JSON response, as in:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

obj_json = JSON.parse(message.payload)
json_id = (obj_json['glossary']['GlossDiv']['GlossEntry']['ID'])
puts json_id

But whenever I get the bottom one as a response, I get the following error:

undefined method `[]’ for nil:NilClass (NoMethodError)

How would I be able to ignore the latter response? I’m probably just thinking too complicated.

Thank you!

>Solution :

ruby has a method called dig that does the existence check for you.

obj_json = JSON.parse(message.payload)
json_id = obj_json.dig('glossary', 'GlossDiv', 'GlossEntry', 'ID')
puts json_id

this will keep going into the JSON until it either returns the value requested or returns nil if any of the keys don’t exist.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading