簡體   English   中英

通過javascript讀取JSON文件

[英]Read JSON file by javascript

我想解析以下 JSON 文件,但我不知道如何解析另一個對象包含的對象。 這是我的代碼:

var myRequest = new Request('test.json');

fetch(myRequest)
  .then(function(response) { return response.json(); })
  .then(function(data) {
          console.log(data. ??????????);

  });

JSON 文件:

{
    "products": {
        "29033669": {
            "anzahl": "11x",
            "img": "https://static.openfoodfacts.org/images/products/29033669/front_de.3.400.jpg",
            "name": "Zitronenteegetränk"
        },
        "4001686386613": {
            "anzahl": "1x",
            "img": "https://static.openfoodfacts.org/images/products/400/168/638/6613/front_de.17.400.jpg",
            "name": "Haribo Saft Goldbären"
        },
        "4008400207322": {
            "anzahl": "5x",
            "img": "https://static.openfoodfacts.org/images/products/400/840/020/7322/front_de.6.400.jpg",
            "name": "Kinder Schokolade"
        },
        "40518152": {
            "anzahl": "4x",
            "img": "https://static.openfoodfacts.org/images/products/40518152/front_en.3.400.jpg",
            "name": "Karamalz classic"
        },
        "676478232": {
            "anzahl": "1x",
            "img": "https://cdn4.iconfinder.com/data/icons/aami-web-internet/64/aami18-38-512.png",
            "name": "Bananen"
        },
        "7613035499768": {
            "anzahl": "4x",
            "img": "https://static.openfoodfacts.org/images/products/761/303/549/9768/front_de.6.400.jpg",
            "name": "Choclait Chips Classic"
        }
    }
}

非常感謝您的幫助! 列維

首先,您必須知道為此使用的數據類型console.log(typeof(data))如果是字符串,則使用const objData=JSON.parse(data)將此字符串解析為對象 現在您可以使用data.products訪問產品。

如果它已經是直接對象類型,您可以使用data.products訪問。

暫無
暫無

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

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