首页 > 解决方案 > 如何从输入文本区域显示 JSON 到 HTML 表

问题描述

我想用 HTML 将 JSON 显示到表格中 在此处输入图像描述

但是,如果使用 javascript 从 textarea 获取价值,是否有可能?所以我想根据值从json显示到表这是我现在正在运行的脚本

<script>
        var el_up = document.getElementById("prettyJSONFormat").value;
        var list = [
         { "col_1": "val_11", "col_3": "val_13" },
            { "col_2": "val_22", "col_3": "val_23" },
            { "col_1": "val_31", "col_3": "val_33" }
        ];

        var list = JSON.parse(el_up)
        el_up.innerHTML = [];
              
        function constructTable(selector) {
              
            // Getting the all column names
            var cols = Headers(list, selector);  
   
            // Traversing the JSON data
            for (var i = 0; i < list.length; i++) {
                var row = $('<tr/>');   
                for (var colIndex = 0; colIndex < cols.length; colIndex++)
                {
                    var val = list[i][cols[colIndex]];
                      
                    // If there is any key, which is matching
                    // with the column name
                    if (val == null) val = "";  
                        row.append($('<td/>').html(val));
                }
                  
                // Adding each row to the table
                $(selector).append(row);
            }
        }
          
        function Headers(list, selector) {
            var columns = [];
            var header = $('<tr/>');
              
            for (var i = 0; i < list.length; i++) {
                var row = list[i];
                  
                for (var k in row) {
                    if ($.inArray(k, columns) == -1) {
                        columns.push(k);
                          
                        // Creating the header
                        header.append($('<th/>').html(k));
                    }
                }
            }
              
            // Appending the header to the table
            $(selector).append(header);
                return columns;
        }       
</script>

这是我的 HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Convert JSON to Table</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<textarea id="prettyJSONFormat" cols=100 rows=20></textarea>
<button onclick = "constructTable('#table')">
        Preview as Table
    </button>

这是我要展示的 json 示例

{
    "Customer":  {
                     "OnSubscription":  true,
                     "Name":  "John",
                     "Surname":  "Smith"
                 },
    "Data":  {
                 "Basket":  [
                                "apples",
                                "pears",
                                "oranges",
                                "strawberries"
                            ]
             }
}

如何从 textarea 中获取值,然后根据值使用表格显示?

标签: javascripthtmljqueryjson

解决方案


我只使用您的示例数据来展示如何做到这一点。

const list = [
  { col_1: "val_11", col_3: "val_13" },
  { col_2: "val_22", col_3: "val_23" },
  { col_1: "val_31", col_3: "val_33" },
];

下面的例子

//initialize textarea value
document.getElementById("prettyJSONFormat").value = 
`[{"col_1":"val_11","col_3":"val_13"},{"col_2":"val_22","col_3":"val_23"},{"col_1":"val_31","col_3":"val_33"}]
`;

function constructTable() {
  const json = document.getElementById("prettyJSONFormat").value;
  const list = JSON.parse(json);

  const tableRows = list.map(el =>
    Object.entries(el).reduce(
      (a, b) => {
        a[b[0].slice(b[0].length - 1) - 1] = b[1];
        return a;
      },
      ["", "", ""]
    )
  );

  const tbody = document.querySelector("#example tbody");
  tbody.innerHTML = "";
  tableRows.forEach(row => {
    const tr = document.createElement("tr");
    row.forEach(r => {
      const td = document.createElement("td");
      td.textContent = r;
      tr.appendChild(td);
    });
    tbody.appendChild(tr);
  });
}
table,
th,
td {
  border: 1px solid black;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Convert JSON to Table</title>
    <link
      rel="stylesheet"
      href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"
    />
    <link
      rel="stylesheet"
      href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css"
    />
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  </head>
  <body>
    <textarea id="prettyJSONFormat" cols="50" rows="4"></textarea>
    <button onclick="constructTable()">Preview as Table</button>
    <table id="example">
      <thead>
        <tr>
          <th>Col1</th>
          <th>Col2</th>
          <th>Col3</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
  </body>
</html>


推荐阅读