Shaonline
Shaonline

Reputation: 1637

how can i test if elements are in json data

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();

Upvotes: 0

Views: 127

Answers (2)

dReAmEr
dReAmEr

Reputation: 7194

Below should work for you

if(data && data.status && data.status.carts){
   console.log("Exist")
} 

Upvotes: 2

PeterKA
PeterKA

Reputation: 24638

If you have:

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

Then to check if carts exists you write:

if( data && data.status && data.status.carts ) {
    //do something
}

Upvotes: 1

Related Questions