How to display a json file in a table [Implementation Code], a json table
<Body> // you must first set up the shelf <table id = "tb" border = "1"> <tr> </ table> // js part <script> // simple json content var json = {"name ": "Zhang San", "Age": "26", "gender": "male"}; // obtain trvar tr = document. getElementsByTagName ('tr'); // it will be used under tr1 and tr2, but it must be declared first, and a null value var tr1 = ''; var tr2 = ''; // use for in for traversal. k is the key and json [k] is the value for (var k in json) {tr1 + = '<th>' + k + '</th> '; tr2 + = '<td>' + json [k] + '</td>';} // The key, that is, name, age, and gender in tr1, then put the information in the first tr [0]. innerHTML = tr1; // The value in tr2 is Zhang San, 26, male. Put the information in the second tr. tr [1]. innerHTML = tr2; </script>
I used to think about how to dynamically put the json content into the table?Sometimes the interview will be asked, of course, the interview will ask how to do it with ajax. But here I will write a simple demo, and put the existing json into the table. I have done this demo several times. Although every time I put it in a table, it looks strange. It may be a vertical bar, for example
Name
Zhang San
Age
26
Gender
Male
This is also possible.
Name
Age
Gender
Zhang San
26
Male
But what I want is
Name, age, gender
Zhang San 26 male
After several experiments, we found that we needed to adjust the structure of the html skeleton. At first, we could not add only the table tag. We had to add two tr tags, finally, use js to fill two tr tags to achieve the desired effect.
In this article, how to display a json file in the table [Implementation Code] is all the content shared by Alibaba Cloud xiaobian. I hope to give you a reference and support for the customer's house.