【问题标题】:Javascript looping through a json object [duplicate]Javascript循环通过json对象[重复]
【发布时间】:2021-10-30 04:58:10
【问题描述】:

我知道这可能已经被问了一百万次,但我花了一整天的时间,我无法解决我的问题。所以就在这里。我有一个以下格式的 json 对象。

所以我试图遍历这个 json 对象,但无法做到。我只是可以让我工作。例如:

const json = [
  [{
    "Id": 1,
    "Name": "Jeffreys Bay",
    "ProvinceID": 1
  }, {
    "Id": 2,
    "Name": "Heidelberg",
    "ProvinceID": 3
  }]
]

for (let x in json) {
  console.log(x + ': ' + json[x]);
}

返回

core.js:6479 ERROR SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at SafeSubscriber._next (location.page.ts:71)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:183)
    at SafeSubscriber.next (Subscriber.js:122)
    at Subscriber._next (Subscriber.js:72)
    at Subscriber.next (Subscriber.js:49)
    at MapSubscriber._next (map.js:35)
    at MapSubscriber.next (Subscriber.js:49)
    at FilterSubscriber._next (filter.js:33)
    at FilterSubscriber.next (Subscriber.js:49)

请帮帮我??

【问题讨论】:

  • 您的代码不会抛出您所说的错误
  • 你拥有的是一个对象数组的数组。和your loop produces no error。哪里有 JSON 被解析?
  • 对象是数组中的一个数组,要么把它变成一个简单的数组,要么在彼此内部运行两个循环。
  • 你有双 [ ] 尝试删除一个。你在那里得到了对象的对象。

标签: javascript


【解决方案1】:

尝试这样做:

const json = [
  [{
    "Id": 1,
    "Name": "Jeffreys Bay",
    "ProvinceID": 1
  }, {
    "Id": 2,
    "Name": "Heidelberg",
    "ProvinceID": 3
  }]
]

for (let x in json) {
  console.log(x + ': ' + JSON.stringify(json[x]));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-22
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-27
    • 2016-10-11
    • 1970-01-01
    相关资源
    最近更新 更多