如何使用 javascript 将下表转换为 JSON?

2023-12-02

如何在 jquery/javascript 中将下表变成 JSON 字符串?

<table>
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>A1</td>
      <td>A2</td>
      <td>A3</td>
    </tr>
    <tr>
      <td>B1</td>
      <td>B2</td>
      <td>B3</td>
    </tr>
    <tr>
      <td>C1</td>
      <td>C2</td>
      <td>C3</td>
    </tr>
  </tbody>
</table>

我想让它能够在变量“myjson”中获取可在 POST 请求或 GET 请求中使用的 JSON 字符串:

{
  "myrows" : [
    {
      "Column 1" : "A1",
      "Column 2" : "A2",
      "Column 3" : "A3"
    },
    {
      "Column 1" : "B1",
      "Column 2" : "B2",
      "Column 3" : "B3"
    },
    {
      "Column 1" : "C1",
      "Column 2" : "C2",
      "Column 3" : "C3"
    }
  ]
}

实现这一目标的最佳方法是什么? (注意:行数可能不同,我只想提取文本,而忽略表内的其他标签)


Update:有一个稍微改进了 jsFiddle 上解决方案的分支(如下).

你只需要遍历你的表的 DOM 并将其读出......这是甚至还没有接近优化但会给你你想要的结果。 (jsFiddle)

// Loop through grabbing everything
var myRows = [];
var $headers = $("th");
var $rows = $("tbody tr").each(function(index) {
  $cells = $(this).find("td");
  myRows[index] = {};
  $cells.each(function(cellIndex) {
    myRows[index][$($headers[cellIndex]).html()] = $(this).html();
  });    
});

// Let's put this in the object like you want and convert to JSON (Note: jQuery will also do this for you on the Ajax request)
var myObj = {};
myObj.myrows = myRows;
alert(JSON.stringify(myObj));​

和输出...

{"myrows":[{"Column 1":"A1","Column 2":"A2","Column 3":"A3"},{"Column 1":"B1","Column 2":"B2","Column 3":"B3"},{"Column 1":"C1","Column 2":"C2","Column 3":"C3"}]}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 javascript 将下表转换为 JSON? 的相关文章

随机推荐