首页 > 解决方案 > 检查嵌套 JSON 中是否存在列

问题描述

下面是我的示例 JSON

{
      "_id":{
         "$oid":"1564t8re13e4ter86"
      },
      "object":{
         "shop":"shop1",
         "domain":"Divers",
         "sell":[
            {
               "location":{
                  "zipCode":"58000",
                  "city":"NEVERS"
               },
               "properties":{
                  "description":"ddddd!!!!",
                  "id":"f1re67897116fre87"
               },
               "employee":[
                  {
                     "name":"employee1",
                     "id":"245975"
                  },
                  {
                     "name":"employee2",
                     "id":"458624"
                  }
               ],
               "customer":{
                  "name":"Customer1",
                  "custid":"test_réf"
               }
               "preference":"talking"
            }
         ]
      }
   }

在上面的示例中,我想知道 $.object.sell.preference 中是否存在此特定列,因为在大多数情况下它不存在导致失败。

如果有任何选项我可以设置为使用 readcontext.read($...) 时返回 null 或空白作为返回,我也很好

提前致谢

问候

标签: javajsonpath

解决方案


注意:我指的是java

是的,可以使用 jsonObject.has() 方法进行检查。假设您有响应变量,其中包含完整的 JSON

你可以这样进行

 JSONObject jsonObject = new JSONObject(response);
 JSONArray jsonArray = jsonObject.getJSONObject("object").getJSONArray("sell");
 for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject jsonObject1 = jsonArray.getJSONObject(i);
    if (jsonObject1.has("preference")) {
        //  Exist
    } else {
        //Not Exist
    }
 }

推荐阅读