【问题标题】:How can I accesss to the elements of array objects?如何访问数组对象的元素?
【发布时间】:2020-11-19 21:37:56
【问题描述】:

如何从这个 json 数据中获取数据?

我从服务器获取这些数据,并使用 sequelize 发送一些数据库的数据。

我要访问的数据是

{result: "[{"userid":"a","speed":10},{"userid":"b","speed":20},{"userid":"c","speed":30}]"}]" }

我试过console.log(result[0].userid);

但是,我只是犯了这样的错误。 ' Uncaught TypeError: Cannot read property 'userid' of undefined'.

你能告诉我我要解决什么吗?

【问题讨论】:

  • JSON.parse(result)
  • @Adam - 不确定这对无效的 JSON 格式有什么帮助

标签: javascript jquery arrays object jquery-plugins


【解决方案1】:

你提供了一个无效的 JSON,json 应该是这样的:

格式化的 JSON 数据

{
  "result":[
    {
      "userid":"a",
      "speed":10
    },
    {
      "userid":"b",
      "speed":20
    },
    {
      "userid":"c",
      "speed":30
    }
  ]
}

然后你就可以访问它了:

const json = {
  "result":[
    {
      "userid":"a",
      "speed":10
    },
    {
      "userid":"b",
      "speed":20
    },
    {
      "userid":"c",
      "speed":30
    }
  ]
};

console.log(json.result[0].userid);

【讨论】:

    【解决方案2】:

    您的 JSON 格式错误。

    试试这个吧……

    {"result":[{"userid":"a","speed":10},{"userid":"b","speed":20},{"userid":"c","speed":30}]}
    

    主要问题是......

    {result: "[{"userid"
    

    应该是……

    {"result":[{"userid"
    

    和

    "speed":30}]"}]" }
    

    应该是……

    "speed":30}]}
    

    请注意,项目之间的空格没有区别,但我已删除以减小 JSON 字符串的大小

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-10
      • 2018-05-30
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      • 2015-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多