简体   繁体   English

如何在 html 表中打印此 JSON

[英]How to print this JSON in an html table

I have a json that I want to print in html an table.我有一个 json 我想在 html 一张桌子上打印。 I just don't know how to print this JSON.我只是不知道如何打印这个 JSON。

I tried this data['videos'] but nothing comes and this as well data.videos我试过这个 data['videos'] 但什么也没出现,这也是 data.videos

{
  "videos": [
    {
      "title": "Martin Garrix feat. Bonn - No Sleep (Official Video)",
      "link": "/watch?v=JxzKNHfNRdI",
      "id": "JxzKNHfNRdI"
    },
    {
      "title": "Wiz Khalifa - No Sleep [Music Video]",
      "link": "/watch?v=KuVAeTHqijk",
      "id": "KuVAeTHqijk"
    },
    {
      "title": "Martin Garrix - No Sleep ft. Bonn (Lyrics)",
      "link": "/watch?v=c3uxLHn3-JQ",
      "id": "c3uxLHn3-JQ"
    },
    {
      "title": "Wiz Khalifa - No Sleep (D33pSoul Remix)",
      "link": "/watch?v=g5Yv00RsCe8",
      "id": "g5Yv00RsCe8"
    },
    {
      "title": "Wiz Khalifa - No Sleep [LYRICS ON SCREEN]",
      "link": "/watch?v=xkLzpRA5W_E",
      "id": "xkLzpRA5W_E"
    }
  ]
}

How do I print a table in HTML (using javascript).如何在 HTML 中打印表格(使用 javascript)。 these details are in "data" variable.这些细节在“数据”变量中。

You need first to define a table in your html.您首先需要在 html 中定义一个table

In javascript, you can retrieve this html element using querySelector('table') .在 javascript 中,您可以使用querySelector('table')检索此 html 元素。

Then you can use insertRow and insertCell to add the elements in the table.然后您可以使用insertRowinsertCell来添加表格中的元素。

 const data = { "videos": [ { "title": "Martin Garrix feat. Bonn - No Sleep (Official Video)", "link": "/watch?v=JxzKNHfNRdI", "id": "JxzKNHfNRdI" }, { "title": "Wiz Khalifa - No Sleep [Music Video]", "link": "/watch?v=KuVAeTHqijk", "id": "KuVAeTHqijk" }, { "title": "Martin Garrix - No Sleep ft. Bonn (Lyrics)", "link": "/watch?v=c3uxLHn3-JQ", "id": "c3uxLHn3-JQ" }, { "title": "Wiz Khalifa - No Sleep (D33pSoul Remix)", "link": "/watch?v=g5Yv00RsCe8", "id": "g5Yv00RsCe8" }, { "title": "Wiz Khalifa - No Sleep [LYRICS ON SCREEN]", "link": "/watch?v=xkLzpRA5W_E", "id": "xkLzpRA5W_E" } ] } const table = document.querySelector('table') for (const video of data.videos) { const row = table.insertRow() for (const value of Object.values(video)) { const cell = row.insertCell() cell.innerHTML = value } }
 table tr td { padding: 5px; }
 <table border=1> <tr> <th>title</th> <th>link</th> <th>id</th> </tr> </table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM