【问题标题】:JSON.parse returning [Object Object] instead of valueJSON.parse 返回 [Object Object] 而不是值
【发布时间】:2018-05-24 00:59:42
【问题描述】:

我的 API 返回 JSON 值,例如

[{"UserName":"xxx","Rolename":"yyy"}]

我需要 UsernameRoleName 值,我试过 JSON.parse 但它返回 [Object Object] 请帮助我提前谢谢

【问题讨论】:

  • 投票以拼写错误/不可复制/未来对其他人无用。解析工作得很好;只是当你输出第一个元素时,你只是在输出对象,而不是它的一个属性。对象上的默认toString 输出[object Object](如果它是普通对象)。
  • 欢迎来到 Stack Overflow!请使用tour,环顾四周,并通读help center,尤其是How do I ask a good question?,向我们展示产生您描述的输出的代码。

标签: javascript html json


【解决方案1】:

考虑以下几点:

    var str = '[{"UserName":"xxx","Rolename":"yyy"}]'; // your response in a string
    var parsed = JSON.parse(str); // an *array* that contains the user
    var user = parsed[0];         // a simple user
    console.log(user.UserName);   // you'll get xxx
    console.log(user.Rolename);   // you'll get yyy

【讨论】:

    【解决方案2】:

    如果你的数据是一个字符串,那么你需要用JSON.parse()解析它,否则你不需要,你只需按原样访问它。

    // if data is not in string format
    const data = [{"UserName":"xxx","Rolename":"yyy"}];
    
    const username = data[0].UserName
    const rolename = data[0].Rolename
    
    console.log(username)
    console.log(rolename)
    
    // if data is in string format
    const strData = JSON.parse('[{"UserName":"xxx","Rolename":"yyy"}]');
    
    const Username = strData[0].UserName
    const Rolename = strData[0].Rolename
    
    console.log(Username)
    console.log(Rolename)

    【讨论】:

      【解决方案3】:

      您有一个array。然后需要首先获取0th元素

      这会起作用

      let unps =  JSON.parse('[{"UserName":"xxx","Rolename":"yyy"}]')[0]
      console.log(unps.UserName, unps.Rolename);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-17
        • 2016-03-19
        • 1970-01-01
        • 2020-04-12
        相关资源
        最近更新 更多