0

Hey guys i am using this lib to convert html table to json array.

http://lightswitch05.github.io/table-to-json/

With this my table is transformed into many objects and it shows it in the chrome console.

It works when i am on the same page as the table but i want to get the json onto another page. Initially i did this to target my element and get it to transform it but no luck any ideas?

$.get("http://support.jonar.com/support/default.asp?W2305", function(data) {
    var table_csv = $("table.testtable").html(data); //this gives me the entire html doc
    console.log(table_csv);
    var myjson = $(table_csv).tableToJSON();
});

This returns the whole document.. for table_csv. Also when i store the html <table></table> into a variable and i run $(table_csv).tableToJSON(); i get an empty value i only see []

Thanks guys!

1 Answer 1

1

You can use Range.createContextualFragment to turn the data into an DocumentFragment.

Then, you can use querySelector to find your table, and get it with jQuery to call tableToJSON.

var frag = document.createRange().createContextualFragment(data);
$(frag.querySelector('table')).tableToJSON();

UPDATE

Since it's not working, probably it's because tableToJSON requires that the element is placed inside the document to work. So, you can do something like that:

var frag = document.createRange().createContextualFragment(data);
var tbl = frag.querySelector('table');
document.body.appendChild(tbl);
var myjson = $(tbl).tableToJSON();
tbl.parentNode.removeChild(tbl);

That way, you append the table to the document temporarly only to get the JSON, and immediately remove it as soon as the json was generated. Leave a comment if that solution doesn't work either.

Sign up to request clarification or add additional context in comments.

7 Comments

$.get( "http://support.jonar.com/support/default.asp?W2305", function( data ) { var frag = document.createRange().createContextualFragment(data); $(frag.querySelector('table.testtable')).tableToJSON(); console.log(frag); }); this returns the whole document again.. its really weird. @Buzinas
@RajaSharma If you log the hole frag you're right, but if you log frag.querySelector('table'), you're not.
ok so the frag.querySelector('tabletest') worked.. when i store this in a variable and try to use it with console.log($(mytable).tableToJSON()); the array is empty @Buzinas Thanks buddy
it worked well it generates many objects... can i ask you another question in chat? @Buzinas
@RajaSharma sure, feel free ;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.