iT邦幫忙

1

後端查詢出之json格式, javascript如何轉成表格顯示出來

@GetMapping(path = "/all")
	public @ResponseBody Iterable<User> getAllUser() {
		return userRepository.findAll();
	}
@Table(name= "user")
@Entity
public class User {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;
	private String name;
	private String email;
	private String password;
[{"id":1,"name":"Jay","email":"Jay@gmail.com","password":"123456"},{"id":2,"name":"Briton","email":"Briton@gmail.com","password":"123456"},{"id":4,"name":"Tony","email":"Tony@gmail.com","password":"123456"}]
1
暐翰
iT邦大師 1 級 ‧ 2020-08-21 15:01:25

可以使用 javascript 將 json 轉成 html table , 以下是 JQuery 版本 :
另外也有 vue,angular 版本 , 只是那需要 nodejs 支持 , 等你需要進階再去搜尋就好

xxx

demo link :
https://www.w3schools.com/code/tryit.asp?filename=GHYGTEA5D18G

<html>

<head>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"
        integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
</head>

<body>
    <div id="table"></div>


    <script type="text/javascript">
        function json2table(jsonString, $table) {
            var json = JSON.parse(jsonString);
            var cols = Object.keys(json[0]);

            var headerRow = '';
            var bodyRows = '';

            function capitalizeFirstLetter(string) {
                return string.charAt(0).toUpperCase() + string.slice(1);
            }

            $table.html('<thead><tr></tr></thead><tbody></tbody>');

            cols.map(function (col) {
                headerRow += '<th>' + capitalizeFirstLetter(col) + '</th>';
            });

            json.map(function (row) {
                bodyRows += '<tr>';

                cols.map(function (colName) {
                    bodyRows += '<td>' + row[colName] + '</td>';
                })

                bodyRows += '</tr>';
            });

            $table.find('thead tr').append(headerRow);
            $table.find('tbody').append(bodyRows);
        }


        // ==== DEMO ====

        var json = `
[{\"id\":1,\"name\":\"Jay\",\"email\":\"Jay@gmail.com\",\"password\":\"123456\"},{\"id\":2,\"name\":\"Briton\",\"email\":\"Briton@gmail.com\",\"password\":\"123456\"},{\"id\":4,\"name\":\"Tony\",\"email\":\"Tony@gmail.com\",\"password\":\"123456\"}]     
        `;
        json2table(json, $("#table"));
    </script>
</body>

</html>
1
通靈亡
iT邦研究生 3 級 ‧ 2020-08-21 15:40:12

這是原生Javascript JSON 轉 Table,不相依JQuery
如果是用JQuery可以用暐翰大大的方式會更簡潔:

https://codepen.io/ted59438/pen/Rwaogjg

淺水員 iT邦研究生 2 級 ‧ 2020-08-21 15:57:42 檢舉

湊熱鬧

function json2Table(json, colNames) {
    let tbCfg=[
        {tag:'thead', tag2:'th', data:[colNames]},
        {tag:'tbody', tag2:'td', data:json, keys:colNames},
    ];
    return tbCfg.reduce((tb, cfg)=>{
        if(cfg.keys===undefined) {
            cfg.keys=cfg.data[0].map((x, i)=>i);
        }        
        tb.appendChild(cfg.data.reduce((tag, row)=>{
            tag.appendChild(cfg.keys.reduce((tr, k)=>{
                let cell=document.createElement(cfg.tag2);
                cell.textContent=row[k];
                tr.appendChild(cell);
                return tr;
            }, document.createElement('tr')));
            return tag;
        }, document.createElement(cfg.tag)));
        return tb;
    }, document.createElement('table'));
}
let tb=json2Table(json, ['id', 'name', 'email', 'password']);
document.body.appendChild(tb);
1
listennn08
iT邦高手 7 級 ‧ 2020-08-21 15:46:42

如果有使用 ES6 的話...

const jsonToHTML = (json) => {
	json = JSON.parse(json);
	let title = `<thead><tr>${Object.keys(json[0]).map((el) => `<th>${el}</th>`).join('')}</tr></thead>`;
	let trs = json.map((el) => Object.values(el).map((td) => `<td>${td}</td>`).join(''));
	let tbody = `<tbody>${trs.map((el) => `<tr>${el}</tr>`).join('')}</tbody>`
	let table = `<table>${title}${tbody}</table>`
	document.querySelector('body').innerHTML = table;
}
const json = "[{\"id\":1,\"name\":\"Jay\",\"email\":\"Jay@gmail.com\",\"password\":\"123456\"},{\"id\":2,\"name\":\"Briton\",\"email\":\"Briton@gmail.com\",\"password\":\"123456\"},{\"id\":4,\"name\":\"Tony\",\"email\":\"Tony@gmail.com\",\"password\":\"123456\"}]"

jsonToHTML(json);

codepen

我要發表回答

立即登入回答