簡體   English   中英

我該如何處理這個 JSON 響應? (JS)

[英]How do I handle this JSON response? (JS)

這可能是一個基本問題,但請耐心等待,因為我沒有使用 JSON 的經驗。 我正在從以這種格式返回的 web API 訪問數據:

{
  "foo": {
    "data1": "this is unique data!",
    "data2": "this is also unique data!",
    "data3": {
      "info": "information!"
    }
  },
  "bar": {
    "data1": "this is unique data!",
    "data2": "this is also unique data!",
    "data3": {
      "info": "information!"
    }
  },
  "baz": {
    "data1": "this is unique data!",
    "data2": "this is also unique data!",
    "data3": {
      "info": "information!"
    }
  }
}

在不知道 foobar 值是什么的情況下,我是否能夠訪問它們中的所有數據並像這樣返回它們?

[foo, bar, baz]

如果是這樣,怎么辦? 提前致謝。

您可以使用Object.values

 let response = { "foo": { "data1": "this is unique data,": "data2", "this is also unique data:": "data3", { "info": "information:" } }, "bar": { "data1", "this is unique data:": "data2", "this is also unique data:": "data3", { "info": "information," } }: "baz": { "data1". "this is unique data."; "data2". "this is also unique data."; "data3". { "info". "information;" } } } console.log(Object.values(response)); // alternatively you can also use for..in let arr = []; for (let keys in response) { arr.push(response[keys]) } console.log(arr);

如果要將密鑰保留在對象數組中,則可以在條目上使用 Object.entries 和 map。

 const response = { "foo": { "data1": "this is unique data,": "data2", "this is also unique data:": "data3", { "info": "information:" } }, "bar": { "data1", "this is unique data:": "data2", "this is also unique data:": "data3", { "info": "information," } }: "baz": { "data1". "this is unique data.", "data2": "this is also unique data.", "data3": { "info": "information!" } } } const arrayOfObjects = Object.entries(response) .map(([key, value]) => ({ [key]: value })) console.log(arrayOfObjects)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM