使用 JavaScript 将 JSON 数据显示到 HTML 页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47850980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:38:18  来源:igfitidea点击:

Display JSON data to HTML page using JavaScript

javascriptjson

提问by Jessica

First time being exposed to JSON so please explain like I'm 5 without the jargon. I have been given a JSON file like this and need to display these items in a list in HTML. A lot of examples have the JSON object assigned to a variable- this isn't assigned to a variable so I'm unsure how to reference it. How can I access and display everything in product list. In my html I have linked to a script.js file and also this json file.

第一次接触 JSON,所以请像我 5 岁一样解释一下,没有行话。我收到了一个这样的 JSON 文件,需要在 HTML 列表中显示这些项目。很多示例都将 JSON 对象分配给了一个变量——它没有分配给一个变量,所以我不确定如何引用它。如何访问和显示产品列表中的所有内容。在我的 html 中,我链接到了一个 script.js 文件和这个 json 文件。

HTML

HTML

  <h1>My Cart</h1>
    <div id="cart">
        <h2>Cart Items</h2>
        <ul id="cartItemsList">
        </ul>
    </div>

JSON

JSON

    "basket": {
        "productList": [{
            "product": {
                "id": "111",
                "name": "Dog",
                "shortDescription": "<p>Mans best friend</p>",
                },
                "category": "Canine",
                "availability": "In Stock",
                "variationType": {
                    "name": "Breed",
                    "value": "Collie"
                }
            },
            "quantity": 1,
            "price": ".00"
        }, {
            "product": {
                "id": "112",
                "name": "Dog",
                "shortDescription": "<p>Not so best friend</p>",
                "category": "feline",
                "availability": "Low In Stock",
                "variationType": {
                    "name": "breed",
                    "value": "Maine Coon"
                }
            },
            "quantity": 1,
            "price": ".00"
        }, {
            "product": {
                "id": "113",
                "name": "Rabbit",
                "shortDescription": "Likes carrots",
                "category": "cuniculus",
                "availability": "In Stock"
            },
            "quantity": 1,
            "price": ".00"
        }]
    }

JavaScript

JavaScript

    var products = document.getElementById("cartItemsList");
    cartItemsList.innerHTML = "<li>" + product + "</li>";

回答by Stacey Reiman

If you are loading this from an external file, you will need Ajax or a similar type of call. To use Ajax, you'll have to add a library called jQuery to your project's HTML file. Then you can call your JSON without referencing it as a javascript variable as you see in the following working code snippet.

如果您从外部文件加载它,您将需要 Ajax 或类似类型的调用。要使用 Ajax,您必须向项目的 HTML 文件中添加一个名为 jQuery 的库。然后您可以调用您的 JSON,而无需将其作为 javascript 变量引用,如您在以下工作代码片段中所见。

/* I put your JSON into an external file, loaded from github */
var url = "https://raw.githubusercontent.com/mspanish/playground/master/jessica.json";

/* this tells the page to wait until jQuery has loaded, so you can use the Ajax call */

$(document).ready(function(){
  $.ajax({
    url: url,
    dataType: 'json',
      error: function(){
        console.log('JSON FAILED for data');
      },
    success:function(results){
  /* the results is your json, you can reference the elements directly by using it here, without creating any additional variables */
  
      var cartItemsList = document.getElementById("cartItemsList");

      results.basket.productList.forEach(function(element) {
      cartItemsList.insertAdjacentHTML( 'beforeend',"<li>" +              element.product.name + " : " + element.price+ " </li>");
      }); // end of forEach
    }  // end of success fn
   }) // end of Ajax call
 }) // end of $(document).ready() function
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h1>My Cart</h1>
<div id="cart">
    <h2>Cart Items</h2>
    <ul id="cartItemsList">
    </ul>
</div>

回答by Rui Paiva

if you want to parse an object:

如果你想解析一个对象:

function logTheObj(obj) {
    var ret = "";
    for (var o in obj) {
        var data = obj[o];
        if (typeof data !== 'object') {
            ret += "<li>" + o + " : " + data + "</li>";
        } else {
            ret += "<li>" + o + " : " + logTheObj(data) + "</li>";
        }
    }
    return "<ul>" + ret + "</ul>";
}

If your object is in a string:

如果您的对象在字符串中:

logTheObj(JSON.parse(jsonString));

回答by Elad

First, you have to convert the jsonfrom long string to acutely js object. you doing so by the JSON.parsecommand. like so:

首先,您必须将json长字符串转换为尖锐的 js 对象。你按照JSON.parse命令这样做。像这样:

let jsObj = JSON.parse( youreJsonString);

Them, you can loop throw youre products in your productList and build your html code, like so:

他们,您可以循环将您的产品扔到您的产品列表中并构建您的 html 代码,如下所示:

var products = document.getElementById("cartItemsList");

jsObj.basket.productList.forEach( function(product ) {
        cartItemsList.innerHTML = "<li>" + product.name + " : " + product.price+ " </li>";
});

回答by Stacey Reiman

Unless you use an Ajax call or something similar to load external JSON, you need to convert the JSON you've provided into an object that you can reference as a variable. Also, your JSON is not valid. I tried correcting it here, and am going to reference your JSON as an object you can reference via a variable named obj. Here is a working code snippet.

除非您使用 Ajax 调用或类似的方法来加载外部 JSON,否则您需要将您提供的 JSON 转换为可以作为变量引用的对象。此外,您的 JSON 无效。我尝试在此处更正它,并将引用您的 JSON 作为您可以通过名为obj的变量引用的对象。这是一个工作代码片段。

var obj = { 
"basket": {
  "productList": [{
   "product": {
    "id": "111",
    "name": "Dog",
    "shortDescription": "<p>Mans best friend</p>",
    "category": "Canine",
    "availability": "In Stock",
    "variationType": {
     "name": "Breed",
     "value": "Collie"
    }
   },
   "quantity": 1,
   "price": ".00"
  }, {
   "product": {
    "id": "112",
    "name": "Dog",
    "shortDescription": "<p>Not so best friend</p>",
    "category": "feline",
    "availability": "Low In Stock",
    "variationType": {
     "name": "breed",
     "value": "Maine Coon"
    }
   },
   "quantity": 1,
   "price": ".00"
  }, {
   "product": {
    "id": "113",
    "name": "Rabbit",
    "shortDescription": "Likes carrots",
    "category": "cuniculus",
    "availability": "In Stock"
   },
   "quantity": 1,
   "price": ".00"
  }]
 }
}

var cartItemsList = document.getElementById("cartItemsList");

obj.basket.productList.forEach(function(element) {
        cartItemsList.insertAdjacentHTML( 'beforeend',"<li>" + element.product.name + " : " + element.price+ " </li>");
});
 <h1>My Cart</h1>
    <div id="cart">
        <h2>Cart Items</h2>
        <ul id="cartItemsList">
        </ul>
    </div>

回答by Brixton Mavu

Javascript Ajax version using external json file from previous answer by Stacey Reiman

Javascript Ajax 版本使用 Stacey Reiman 先前回答中的外部 json 文件

const products = document.getElementById("cartItemsList");

/* get basket items from JSON */
class Basket {
    async cartItems() {
        try {
            let result = await fetch('https://raw.githubusercontent.com/mspanish/playground/master/jessica.json')
            let data = await result.json()
           // return data
            
           /* destructuring data */ 
         let basketItems = data.basket.productList
            basketItems = basketItems.map(item =>{
            const price = item.price
            const{id,name,shortDescription,category,availability} = item.product
            const breed = item.product.variationType
            const quantity = item.quantity
              
            return {price,id,name,shortDescription,category,availability,quantity,breed}
            })
            return basketItems 
            
        } catch (error) {
            console.log(error)  
        }
    }
}
/* Display stuff from the basket */
class Display {
    displayBasket(basket) {
    //console.log(basket)
         let result = ""
        basket.forEach((item)=>{
        result += `
        <li>
        id : ${item.id}
        name: ${item.name}
        price: ${item.price}
        availability: ${item.availability}
        category : ${item.category}
        quantity : ${item.quantity}
        shortDescription : ${item.shortDescription}
        </li>
        `})
        cartItemsList.innerHTML = result 
    }
}

document.addEventListener("DOMContentLoaded", ()=>{
    const basket  = new Basket()
    const display = new Display()

    basket.cartItems().then(basket => display.displayBasket(basket))
})
 <h1>My Cart</h1>
    <div id="cart">
        <h2>Cart Items</h2>
        <ul id="cartItemsList">
        </ul>
    </div>