Bomber
Bomber

Reputation: 10947

javascript check for valid json

I have this if statement looking for a json object:

updateStudentData = function(addUpdateData) {
    var rowDataToSave;

    if(addUpdateData.data.row) {
        rowDataToSave = addUpdateData.data.row;
    } else {
        rowDataToSave = addUpdateData.data;
    }
}

Can anyone please tell me how I can check to see if the json has a row object? Currently I get cannot read row property of undefined.

Upvotes: 0

Views: 1434

Answers (3)

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27192

Try this it will help you :

function isValidJson(jsonData) {
    try {
        JSON.parse(jsonData);
        return true;
    } catch (e) {
        return false;
    }
}
var jsonstr = '{"name":"xyz","Skill":"Javascript"}'
var res = isValidJson(jsonstr);
console.log(res);

Here, we are passing JSON String(jsonstr) into the function isValidJson(jsonstr) and then checked if string is JSON parse or not.

Upvotes: -1

T.J. Crowder
T.J. Crowder

Reputation: 1073988

You have several choices:

1. Testing for truthiness

if (addUpdateData.data && addUpdateData.data.row) {

This would be the most appropriate in your situation, since you're expecting addUpdateData.data to be an object reference.

The next two choices are really only needed if the property may have a falsy value like 0, "", NaN, null, undefined, or (of course) false but you still want to know if the property is there.

2. hasOwnProperty

if (addUpdateData.hasOwnProperty("data") && addUpdateData.data.row) {

This checks to see if addUpdateData has an "own" (not inherited) propety called data. Not necessary in your case.

3. in

if ("data" in addUpdateData && addUpdateData.data.row) {

This checks to see if addUpdateData has a data property (either its own, or one it inherits). Not necessary in your case.

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 190907

you can modify your condition to be if (addUpdateData.data && adUpdateData.data.row)

Upvotes: 4

Related Questions