0

有 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 或任何其他库是否可行?我们可以使用自定义忽略这些字段。但没有找到只忽略对象键并验证子值的方法。

4

1 回答 1

0

使用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
                }
            }
        }
    }
}

JSON路径

$.values.[*]

输出

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

在线测试工具:

  1. JSONLint - JSON 验证器
  2. Jayway JsonPath 评估器
于 2021-11-17T08:42:41.310 回答