通过javascript读取JSON文件

问题描述 投票:-1回答:1

我想解析以下JSON文件,但我不知道如何解析另一个Object包含的Object。这是我的代码:

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"
        }
    }
}

非常感谢您的帮助!列维

javascript json parsing
1个回答
0
投票

首先,您必须知道使用console.log(typeof(data))的数据类型如果它是字符串,则使用const objData=JSON.parse(data)将此字符串解析为对象现在您可以使用data.products来访问产品。

如果它已经是对象类型直接,您可以使用data.products访问。

© www.soinside.com 2019 - 2024. All rights reserved.