【问题标题】:Jsonassert ignore keyJsonassert 忽略键
【发布时间】:2021-12-27 18:47:40
【问题描述】:

有 2 个 Json 字符串要比较。

1

"values": {
    "-1487778947": {
      "field1": "xxx",
      "field2": "yyy",
      "field3": {
        "zzz": {
          "field4": 21,
          "field5": 28
        }
      }
    },
    "-1820451085": {
      "field1": "fgf",
      "field2": "dfd",
      "field3": {
        "zzz": {
          "field4": 56,
          "field5": 78
        }
      }
    },
}

2

"values": {
    "343434-35454-232467498": { // ignore this value
      "field1": "xxx",  // compare these fields
      "field2": "yyy",  // compare these fields
      "field3": {       // compare these fields
        "zzz": {        // compare these fields
          "field4": 21, // compare these fields
          "field5": 28  // compare these fields
        }
      }
    },
    "486787-4546-787344353": { // ignore this value
      "field1": "fgf",   // compare these fields
      "field2": "dfd",   // compare these fields
      "field3": {        // compare these fields
        "zzz": {         // compare these fields
          "field4": 56,  // compare these fields
          "field5": 78   // compare these fields
        }
      }
    },
}

我想忽略这些对象的键,只匹配内部字段。这对 JsonAssert 或任何其他库是否可行? 我们可以使用自定义忽略这些字段。但没有找到只忽略对象键并验证子值的方法。

【问题讨论】:

    标签: json jsonpath jsonassert jsonunit


    【解决方案1】:

    使用Jayway-JSONPath,您只能从两个 JSON 中获取子节点,从而忽略密钥。

    输入 JSON

    {
        "values": {
            "-1487778947": {
                "field1": "xxx",
                "field2": "yyy",
                "field3": {
                    "zzz": {
                        "field4": 21,
                        "field5": 28
                    }
                }
            },
            "-1820451085": {
                "field1": "fgf",
                "field2": "dfd",
                "field3": {
                    "zzz": {
                        "field4": 56,
                        "field5": 78
                    }
                }
            }
        }
    }
    

    JSONPath

    $.values.[*]
    

    输出

    [
       {
          "field1" : "xxx",
          "field2" : "yyy",
          "field3" : {
             "zzz" : {
                "field4" : 21,
                "field5" : 28
             }
          }
       },
       {
          "field1" : "fgf",
          "field2" : "dfd",
          "field3" : {
             "zzz" : {
                "field4" : 56,
                "field5" : 78
             }
          }
       }
    ]
    

    在线测试工具:

    1. JSONLint - The JSON Validator
    2. Jayway JsonPath Evaluator

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 2011-04-24
      • 2021-08-11
      • 2012-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多