Sam Berchmans
Sam Berchmans

Reputation: 127

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

Upvotes: 0

Views: 1242

Answers (2)

Kartik Agarwal
Kartik Agarwal

Reputation: 1403

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

Upvotes: 3

JaySabir
JaySabir

Reputation: 322

try:

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

it will return false if empty and vice versa

Upvotes: 1

Related Questions