在jQuery中将HTML表格数据转换为JSON对象 [英] Convert a HTML table data into a JSON object in jQuery

查看:406
本文介绍了在jQuery中将HTML表格数据转换为JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都知道如何将一个HTML值表转换成一个漂亮的JSON对象来处理jQuery?

解决方案

HTML表格?就像所有的< td> 二维数组中的内容一样?

  var tbl = $('table#whatever tr')。map(function(){
return $(this).find('td')。map(function(){
return $(this).html();
})。get();
))。get();

然后只需使用$ .json(或任何您想要的库)将其转换为JSON字符串。

编辑—重新编写为使用本机(在此
$ b

  .map() var tbl = $('table#whatever tr')。get()。map(function(row){
return $(row).find('td')。get()。map(function ){
return $(cell).html();
});
});

jQuery .map()函数具有将返回的数组展平成结果数组的特征。也就是说,如果回调函数返回一个本身就是一个数组的值,那么不是返回的数组成为 .map()单元格的值c $ c> result,它的元素都被添加到结果中。



它可能会使用原始的jQuery版本,额外数组围绕返回值。


Anyone know how to convert an HTML table of values into a nice JSON object to be manipulated with jQuery?

解决方案

An HTML table? Like, all the <td> contents in a 2-d array?

var tbl = $('table#whatever tr').map(function() {
  return $(this).find('td').map(function() {
    return $(this).html();
  }).get();
}).get();

Then just use $.json (or whatever library you want) to turn that into a JSON string.

edit — re-written to use the native (shim here) .map() from the array prototype:

var tbl = $('table#whatever tr').get().map(function(row) {
  return $(row).find('td').get().map(function(cell) {
    return $(cell).html();
  });
});

The jQuery .map() function has the "feature" of flattening returned arrays into the result array. That is, if the callback function returns a value that is itself an array, then instead of that returned array becoming the value of one cell of the .map() result, its elements are each added to the result.

It might work to use the original jQuery version and just wrap an extra array around the returned values.

这篇关于在jQuery中将HTML表格数据转换为JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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