简体   繁体   English

如何在angularjs中将外部文件中的HTML表转换为JSON

[英]How to convert HTML table in an external file to JSON in angularjs

I have data that is stored in an html table, the file only contains the table and no other HTML components, I would like to know what is the best way to convert the data to a json format in an AngularJS controller, plain JavaScript or jQuery would work as well. 我有存储在html表中的数据,该文件仅包含该表,没有其他HTML组件,我想知道在AngularJS控制器,纯JavaScript或jQuery中将数据转换为json格式的最佳方法是什么也会工作。 I was as also researching if I can apply filter and do calculations on a table imported using ng-include but so far no luck 我也正在研究是否可以对使用ng-include导入的表应用过滤器并进行计算,但到目前为止还没有运气
EDIT So this is how far I got : 编辑所以这是我走了多远:

 $(document).ready(function() {
     $.get("xxxxxxx/test.html", function( my_var ) {
       var arrayOfArray= $('table tr').map(function(){
    return [
        $('td',this).map(function(){
            return $(this).text();
        }).get()
    ];
}).get();
   alert(arrayOfArray);
});



});

I know that the HTML is loading properly as I can see it in the first alert, however the second comes empty 我知道HTML加载正确,因为我在第一个警报中可以看到它,但是第二个警报为空

You can go with jQuery for same. 您可以使用jQuery。 First of all get all your table data into JavaScript array of array using jQuery.fn.map and jQuery.fn.get . 首先,使用jQuery.fn.mapjQuery.fn.get将所有表数据放入JavaScript数组。

 var arrayOfArray= $('table tr').map(function(){
    return [
        $('td',this).map(function(){
            return $(this).text();
        }).get()
    ];
}).get();

Finally Convert this array of array into JSON String. 最后,将此数组数组转换为JSON字符串。

var json = JSON.stringify(arrayOfArray);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM