Folks,
I have the following requirement:
I will have a list of log lines in a HTML table, some of these lines will contain JSON strings, I want to format the JSON in table when the HTML file is loaded from disk. I have it nearly there, see JSFiddle. I just cant seem to get it formatted inside the table cell:
var table = document.getElementById("report");
for (var i = 0, row; row = table.rows[i]; i++)
{
col = row.cells[0];
//if(innerHTML == JSON)
col.innerHTML = (syntaxHighlight(JSON.stringify(col.innerHTML, undefined, 4)));
}
var s = {"Id":"124578","oId":"11","Type":"2"};
var ss = JSON.stringify(s, undefined, 4);
The problem with the formatting inside the cell is that you were calling JSON.stringify
on a string, not an object. Check out this fiddle: http://jsfiddle.net/zu7zs5b1/ . Note this part:
for (var i = 0, row; row = table.rows[i]; i++) {
col = row.cells[0];
//if(innerHTML == JSON)
try {
jsn = JSON.stringify(JSON.parse(col.innerHTML), undefined, 4); // <-- proper JSON str
col.innerHTML = (syntaxHighlight(jsn));
} catch (e) {
console.log("Fail");
}
}
A bit hacky, but it gets the job done.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.