简体   繁体   中英

Check if column exists in Nested JSON

Below is my sample 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"
            }
         ]
      }
   }

In the above sample i would like to know if this particular column exists in the $.object.sell.preference exists, as in most cases it is not existing which is leading to failure.

Also i am good if there is any option i can set to get null or blank as return when using readcontext.read($...)

Thanks in Advance

Regards

NOTE: I'm referring in java

Yes, it is possible to check using jsonObject.has() method. Suppose you have response variable in which you have full JSON

You can proceed it like this

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

try:

bool(json['object']['sell'][0]["preference"])

it will return false if empty and vice versa

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM