从 html 表创建一个 json 数组
我有 C++ 程序将日志文件导出为 HTML 表,我想知道是否有任何方法可以
<table>
<tr><td>id</td><td>value1</td><td>value2</td></tr>
<tr><td>0 </td><td>0 </td><td>0 </td></tr>
<tr><td>0 </td><td>1.5 </td><td>2.15 </td></tr>
</table>
使用 Javascript 函数将该表(类似这样)解析为 JSON 数组(类似这样):
var chartData = [
{id:"0",value1:"0",value2:"0"},
{id:"1",value1:"1.5",value2:"2.15"}];
问题是我希望这个函数适用于给定的每个表,具有任何可能的行或列计数(第一行始终是标题)。
i have C++ program exporting log files as HTML table and I wanted to know if there is any way that i can parse that table(something like this):
<table>
<tr><td>id</td><td>value1</td><td>value2</td></tr>
<tr><td>0 </td><td>0 </td><td>0 </td></tr>
<tr><td>0 </td><td>1.5 </td><td>2.15 </td></tr>
</table>
into a JSON array (something like this) using a Javascript function:
var chartData = [
{id:"0",value1:"0",value2:"0"},
{id:"1",value1:"1.5",value2:"2.15"}];
The problem is that I want this function to work for every table given to it, with any possible row or column count(first row is always a header).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是我的实现:
您可以像这样调用:
查看工作示例→
Here's my implementation:
Which you would invoke like:
See working example →
像这样,假设第一行始终是标题(当然可以更改以使其更加灵活):
用法是:
通过传递格式函数,您可以将每个单元格的值格式化为正确的数据类型。
DEMO
它的工作原理是假设只有一个
tbody
元素。您必须根据您的需要进行调整。Something like this, assuming the first row is always the header (could certainly be changed to make it more flexible):
Usage is:
By passing a format function, you can format the values of each cell into the right data type.
DEMO
It works under the assumption that there is only one
tbody
element. You have to adjust it to your needs.您可以使用 jquery 框架来做到这一点。我
干杯。
You could do it using the jquery framework. I
Cheers.
我需要同样的东西,除了能够忽略列、覆盖值并且不会被嵌套表混淆。我最终编写了一个 jQuery 插件
table-to-json
:https:/ /github.com/lightswitch05/table-to-json
您所要做的就是使用 jQuery 选择表格并调用插件:
以下是使用您的数据进行操作的演示:
http://jsfiddle.net/dGPks/199/
I needed the same thing except with the ability to ignore columns, override values, and not be confused by nested tables. I ended up writing a jQuery plugin
table-to-json
:https://github.com/lightswitch05/table-to-json
All you have to do is select your table using jQuery and call the plugin:
Here is a demo of it in action using your data:
http://jsfiddle.net/dGPks/199/
由于该表格式看起来像格式良好的 XML,因此我将使用 XSLT 进行转换;然后您的 C++ 程序就可以调用 XSLT 引擎。
Since that table format looks like well-formed XML, I'd use XSLT to make the conversion; your C++ program could then just invoke an XSLT engine.