Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if it is a JsonArray or JsonObject in Javascript

So my json data is something like the following,

{
  "amazon": []
},
{
  "flipkart": {
    "product_store": "Flipkart",
    "product_store_logo": "logo url",
    "product_store_url": "shop url",
    "product_price": "14999",
    "product_offer": "",
    "product_color": "",
    "product_delivery": "3-4",
    "product_delivery_cost": "0",
    "is_emi": "1",
    "is_cod": "1",
    "return_time": "10 Days"
  }
},
{
  "snapdeal": []
}

So here I want to loop through each shop and check if it is a jsonarray(amazon) or jsonobject(flipkart) then delete those empty array. And add it to a new array.

Just like the example all keys who have no values like amazon and snapdeal are arrays. And keys with values are jsonObject. I can't change the json.

So I want to know how can I detect JSONObject and JSONArray...

Thank you..

like image 801
Bucky Avatar asked Dec 05 '22 13:12

Bucky


1 Answers

You can use Array.isArray to check if it is array:

if (Array.isArray(json['amazon'])) {
  // It is array
} 

and you can check if type of object is object to determine if it is an object. Please refer, for example, this answer for the reason why check for null is separate:

if (json['flipkart'] !== null && typeof (json['flipkart']) === 'object') {
  // It is object
}
like image 101
Flying Avatar answered Mar 03 '23 00:03

Flying