How to display a json file in a table [Implementation Code], a json table

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.