如何使用javascript将下表转换为JSON? [英] How to convert the following table to JSON with javascript?

查看:140
本文介绍了如何使用javascript将下表转换为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to make the following table into a JSON string in jquery/javascript?

<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中获取一个JSON字符串用于POST请求或GET请求:

I want to make it such that I can get a JSON string in a variable "myjson" that could be used in a POST request or GET request:

{
  "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"
    }
  ]
}

完成此任务的最佳方法是什么? (注意:可能有不同数量的行,我只想提取文本而忽略表中的其他标记)

What is the best way to accomplish this? (Note: There may be a varying number of rows, I just want to extract the text while ignoring the other tags inside of the table)

推荐答案

更新: jsFiddle上有一个解决方案的略微改进(下面)。

Update: There's a slightly improved fork of the solution (below) on jsFiddle.

你只需要走出你的桌子的DOM读出来......这甚至没有接近优化但是给你想要的结果。 ( jsFiddle

You just need to walk the DOM of your table reading it out... this is not even close to optimized but will give you the result you want. (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"}]}

这篇关于如何使用javascript将下表转换为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆