在chrome网络->预览窗口中,我具有以下结构如下的对象:
n_days_orders:
index: ["Sun, 21 Oct 2018", "Mon, ...
last_n: 7
quantity: [0, 0, 0, 0, 0, 0, 0]
我正在使用以下内容检查是否是JSON对象以及是否解析它。
How can I check if a value is a json object?
之后function isJSON (something) {
if (typeof something !== 'string') {
something = JSON.stringify(something)
}
try {
JSON.parse(something)
return true
} catch (e) {
return false
}
}
if (isJSON(data.n_days_orders)) {
try {
daysOrders = JSON.parse(data.n_days_orders)
} catch (e) {
console.log(e.message)
//the line below is printed
>>Unexpected token o in JSON at position 1
}
}
如何在不引发错误的情况下获取对象中的值?
答案 0 :(得分:1)
尝试使用isJSON作为解析器来检测并尝试解析该值或引发错误。 一种访问obj属性而又不存在引用问题的方法是通过索引值
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
检查字符串是否为有效JSON的正确方法是尝试解析它并处理异常。
js typeof
比较将返回'object'
。
如果您愿意创建模型描述的JSON格式的原型或检查器,则一种方法是在循环中检查其字段并检查其存在,但这将使您花费每个O(props)表示法对象,所以要注意延误。
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
但是我想您只想检查属性是否存在
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