0

I need to check if an element is in json data.

JSON data

{
    "status": {
        "carts": [
            {
                "service": "page-mailer",
                "running": "",
                "last success": "2015-05-07 09:35:31"
            }
        ],
        "pages": [
            {
                "service": "page-mailer",
                "running": "",
                "last success": "2015-05-07 09:35:31"
            }
        ],
        "actions": [
            {
                "service": "page-mailer",
                "running": "",
                "last success": "2015-05-07 09:35:31"
            }
        ],
        "integrations": [],
        "service": [
            {
                "service": "page-mailer",
                "running": "",
                "last success": "2015-05-07 09:35:31"
            }
        ],
        "smtp": [
            {
                "Server": "myserver"
            }
        ],
        "servers": []
    },
    "timing": "2ms"
}

Something like,

if(carts){}  
if(pages){} etc

i am using jquery getJSON();

Barmar
  • 596,455
  • 48
  • 393
  • 495
Shaonline
  • 1,307
  • 5
  • 16
  • 30

2 Answers2

2

Below should work for you

if(data && data.status && data.status.carts){
   console.log("Exist")
} 
dReAmEr
  • 6,182
  • 7
  • 34
  • 52
1

If you have:

var data = {"status": { "carts": ....... } }

Then to check if carts exists you write:

if( data && data.status && data.status.carts ) {
    //do something
}
PeterKA
  • 21,234
  • 4
  • 21
  • 44
  • Thank you, i believe my question didn't cover the part to find out if there are any records in carts or not. I want to execute if(data.status && data.status.carts){} only if it is not empty. would this condition work for that? – Shaonline May 11 '15 at 16:56
  • Yes, it would -- that's what it checks. – PeterKA May 11 '15 at 16:58
  • You need to check using `if(data && data.status && data.status.carts && data.status.carts.length)`. But if `data.status.carts` is always defined (even empty), you could just check for `if(data.status.carts.length)` – A. Wolff May 11 '15 at 17:03