Try isJSON as a parser to detect and try parse the value or throw an error.
A way to access obj property without having problems with its existence on a reference is by the index value
let t = data.n_days_orders //will raise an exception if the field does not exist;
let tmp = data['n_days_orders'] //will allow you the cast and return an undefined value
A proper way to check a string if it is a valid JSON is to try to parse it and handle an exception.
js typeof
comparison will return 'object'
.
If you are willing to create a prototype or a checker of a JSON format described by a model, a way is to check its fields in a loop and check their existence but this will cost you an O(props) notation for each object so care for delays.
function checkMyModel(model , prototypemodel){
let props = Object.keys(prototypemodel);
let notexist = props.filter((p)=>{
return (model[p] === undefined );
})
console.log(notexist);
return notexist.length > 0 ? false : true;
}
var proto = {id: null, name:null , value:null , z : null }
var m1 = {id: 1, name:'john' , z : null }
var m2 = {id: 1, name:'john1' ,value:'iam a value2'}
var m3 = {id: 1, name:'john2' ,value:'iam a value3' , z : 34 }
console.log(checkMyModel(m1,proto)); //false missing value
console.log(checkMyModel(m2,proto)); //false missing z
But I suppose you want to check only if the property exists
function isJSON (something) {
try {
return(typeof something !== 'object') ? JSON.parse(something) : something;
} catch (e){ console.warn(e);throw e; }
}
function getDayOrdes (value){
try {
let obj = isJSON(value);
let t= obj['n_days_orders'] ;
return (t !== null && t !== undefined) ? t : [];
} catch (e) { return e.message; }
}
var obj1 = { id : 'order1' , value : '111$'}, obj2 = { id : 'order2' , value : '222$'};
var json1 = { id: '' , n_days_orders: [obj1 , obj2]};
var json2 = JSON.stringify(json1) ,json3 = { id: 1 , values: [obj1 , obj2]};
console.log(getDayOrdes(json1)); //returns obj
console.log(getDayOrdes(json2 + 'zasaza')); //throws json parse error
console.log(getDayOrdes(json2)); //returns obj
console.log(getDayOrdes(json3)); //undefined n_days_orders does not exist