gpt4 book ai didi

javascript - 无法从 Ajax 请求中读取 Javascript 对象

转载 作者:行者123 更新时间:2023-12-03 00:51:13 24 4
gpt4 key购买 nike

我在 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
}
}

如何获取对象中的值而不引发错误?

最佳答案

尝试使用 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 格式的原型(prototype)或检查器,一种方法是在循环中检查其字段并检查它们是否存在,但这将花费您每个 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

关于javascript - 无法从 Ajax 请求中读取 Javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53032403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com