John Wick
John Wick

Reputation: 509

Loop over JSON api

I have an API call which returns an object, I would like to check if some of the values returns null.

API response structure looks like:

{
    "expirationDate": "August 31, 2016",
    "remainingDays": 127,
    "pid": "null",
    "seats": [{
        "activeStatus": "Y",
        "pid": "TE80",
        "firstName": "Lenovo X230 Beta SN",
        "guid": "0CA6A94E378F464E9A5EC09102779CFC"
    }]
}

Thank you in advance.

Upvotes: 0

Views: 698

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386540

You could iterate over all properties and if the value is an array, then over all elements of the array and check if one property value is null or 'null'.

function hasNull(o) {
    return Object.keys(o).some(function (k) {
        return Array.isArray(o[k]) && o[k].some(hasNull) || o[k] === null || o[k] === 'null';
    });
}

var data = { "expirationDate": "August 31, 2016", "remainingDays": 127, "pid": "null", "seats": [{ "activeStatus": "Y", "pid": "TE80", "firstName": "Lenovo X230 Beta SN", "guid": "0CA6A94E378F464E9A5EC09102779CFC" }] },
    hasNullValue = hasNull(data);

console.log(hasNullValue);

Upvotes: 1

vaso123
vaso123

Reputation: 12391

You just need to iterate through the object keys, and check their values.

The best way, if you put this for loop into a function and then if an object appears, you can use a recursion on that.

var json = {
    "expirationDate": "August 31, 2016",
    "remainingDays": 127,
    "pid": "null",
    "seats": [{
            "activeStatus": "Y",
            "pid": "TE80",
            "firstName": "Lenovo X230 Beta SN",
            "guid": "0CA6A94E378F464E9A5EC09102779CFC"
        }]
};

for (prop in json) {
    if (typeof json[prop] === 'object') {
        //do a recursion here
    } else {
        if (json[prop] === 'null') {
            //do what you want with null
            console.log("It is null");
        }
    }
}

Upvotes: 2

Related Questions