Home > database >  Ruby - ignore empty JSON response?
Ruby - ignore empty JSON response?

Time:11-29

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:

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!

CodePudding user response:

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.

CodePudding user response:

Add a condition to check that GlossEntry exists json_id = obj_json['glossary']['GlossDiv']['GlossList']['GlossEntry'] ? obj_json['glossary']['GlossDiv']['GlossList']['GlossEntry']['ID'] : ''

  • Related