【问题标题】:Cant read Javascript object from Ajax request无法从 Ajax 请求中读取 Javascript 对象
【发布时间】:2019-04-01 14:41:03
【问题描述】:

我在 chrome network-> 预览窗口中有以下结构如下的对象:

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

如何在不抛出错误的情况下获取对象中的值?

【问题讨论】:

  • 有什么问题?你没有说你到底在追求什么,为什么现在的方式不适合你
  • 你需要先解析data。在将字符串转换为对象之前,字符串不会具有 n_days_orders 之类的属性
  • 该错误通常意味着数据已经是一个对象,而不是JSON字符串,因此无需对其调用JSON.parse
  • There is no such thing as a "JSON Object"isJSON({}) 计算结果为 true,但 {} 根本不是 JSON。
  • (记住 JSON 是一个 string 可以转换成一个对象;它不是对象本身。假设您通过 jQuery AJAX 请求获取此数据,它是可能在此代码运行之前已经为您完成了转换;它会根据响应 MIME 类型或调用中声明的 dataType 自动执行此操作。)

标签: javascript json


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-02
    • 2018-05-23
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    相关资源
    最近更新 更多