检查 JSON 的嵌套元素是否存在于 ruby 中

Checking if nested element of JSON exists in ruby

我在 structure 字段中存储了以下 JSON。我想检查键 structure[cluster][ID] 是否存在于三元运算符中 ruby。

{
        "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
        }
    }

例子

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

根级属性与 has_key? 配合良好 - 我无法检查嵌套级元素是否存在。感谢任何帮助。

我建议使用散列 #dig 方法,它可以让您安全地浏览散列级别。另外,不使用三进制,只需将测试值存在的 true/false 值分配给 newField,如果更适合则转换为字符串...

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