Home > database >  Checking if nested element of JSON exists in ruby
Checking if nested element of JSON exists in ruby

Time:03-09

I have the following JSON stored in the structure field. I want to check if the key structure[cluster][ID] exists with ruby within a ternary operator.

{
        "ID": "client DEF",
        "cluster": {
            "ID": "cluster 789",
            "flights": 4,
            "profit": 5245,
            "clv": 2364
        },
        "segment": {
            "ID": "segment 876",
            "flights": 2,
            "profit": 2150,
            "clv": 1564
        },
        "node": {
            "xpos": 1,
            "ypos": 2
        }
    }

Example

structure.has_key?(cluster.ID) ? structure["newField"] = "true" :structure["newField"] = "false"

Root level attributes work well with has_key? - I am not able to check exists on a nested level element. Any help is appreciated.

CodePudding user response:

I'd suggest using the hash #dig method which lets you safely navigate levels of the hash. Also, instead of using a ternary, just assign the true/false value of the presence of the tested value to the newField, converted to a string if that better suits...

structure['newField'] = structure.dig(:cluster, :id).present?.to_s
  • Related