Rewrite json

 1 <!DOCTYPE html>
 2 <html>
 3   <head>
 4     <meta charset="utf-8">
 5     <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
 6     <meta name="viewport" content="width=device-width">
 7 
 8     <title>Fetch json example</title>
 9 
10     <link rel="stylesheet" href="style.css">
11     <!--[if lt IE 9]>
12       <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
13     <![endif]-->
14   </head>
15 
16   <body>
17     <h1>Fetch json example</h1>
18     <ul>
19     </ul>
20 
21   </body>
22   <script>
23     var myList = document.querySelector('ul');
24 
25     fetch('products.json')
26     .then(function(response) {
27       if (!response.ok) {
28         throw new Error("HTTP error, status = " + response.status);
29       }
30       return response.json();
31     })
32     .then(function(json) {
33       for(var i = 0; i < json.products.length; i++) {
34         var listItem = document.createElement('li');
35         listItem.innerHTML = '<strong>' + json.products[i].Name + '</strong>';
36         listItem.innerHTML +=' can be found in ' + json.products[i].Location + '.';
37         listItem.innerHTML +=' Cost: <strong>£' + json.products[i].Price + '</strong>';
38         myList.appendChild(listItem);
39       }
40     })
41     .catch(function(error) {
42       var p = document.createElement('p');
43       p.appendChild(
44         document.createTextNode('Error: ' + error.message)
45       );
46       document.body.insertBefore(p, myList);
47     });
48 
49   </script>
50 </html>
1 { "products" : [
2   { "Name": "Cheese", "Price" : 2.50, "Location": "Refrigerated foods"},
3   { "Name": "Crisps", "Price" : 3, "Location": "the Snack isle"},
4   { "Name": "Pizza", "Price" : 4, "Location": "Refrigerated foods"},
5   { "Name": "Chocolate", "Price" : 1.50, "Location": "the Snack isle"},
6   { "Name": "Self-raising flour", "Price" : 1.50, "Location": "Home baking"},
7   { "Name": "Ground almonds", "Price" : 3, "Location": "Home baking"}
8 ]}

原文地址:https://www.cnblogs.com/BigWatermelon/p/10052782.html