Reputation: 10947
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
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
Reputation: 1073988
You have several choices:
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.
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.
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
Reputation: 190907
you can modify your condition to be if (addUpdateData.data && adUpdateData.data.row)
Upvotes: 4