如何将指定JSON格式字符串转换为可填充HTML表格的数组?
解决JSON转表格数据的问题
首先得提一下,你给的JSON字符串少了个末尾的},这会导致解析失败,先补全它:
var str = '{ "abc": { "decline_reason": "Business rule switched off" }, "def": { "decline_reason": "No response by interface" }, "ghi": { "decline_reason": "Requested incorrect size" } }';
接下来,咱们一步步把这个字符串转换成能填充表格的数组,还能顺便优化你当前的表格渲染方式:
1. 解析JSON并提取目标数据
别用正则啦,处理JSON最靠谱的就是原生的JSON.parse()。解析之后,我们可以用Object.entries()把对象转成键值对数组,再提取出需要的参考码和拒绝原因:
// 把字符串转成JS对象 const parsedData = JSON.parse(str); // 转换成[参考码, 拒绝原因]的二维数组 const declines = Object.entries(parsedData).map(([code, details]) => [ code, details.decline_reason ]);
现在declines数组就是你需要的结构:
[ ["abc", "Business rule switched off"], ["def", "No response by interface"], ["ghi", "Requested incorrect size"] ]
2. 动态渲染表格(比硬编码更灵活)
你现在的表格是硬写了一行,要是以后数据变多了就得手动加行,太麻烦。咱们用JS动态生成所有行,不管有多少条数据都能自动适配:
先简化你的HTML(只留表头)
<table id="declinesTable"> <tr> <th onclick="sortTable(0)">Reference Code</th> <th>Decline Reason</th> </tr> <!-- 动态行会在这里生成 --> </table>
然后写动态生成的JS代码
const table = document.getElementById('declinesTable'); // 遍历declines数组,逐个创建表格行 declines.forEach(([code, reason], idx) => { // 创建行元素 const row = document.createElement('tr'); row.id = `lender${idx + 1}`; // 可选:给行设置id // 创建参考码单元格 const codeCell = document.createElement('td'); codeCell.textContent = code; // 可选:给单元格设置id -> codeCell.id = `lender${idx + 1}`; // 创建拒绝原因单元格 const reasonCell = document.createElement('td'); reasonCell.textContent = reason; // 可选:给单元格设置id -> reasonCell.id = `declineReason${idx + 1}`; // 把单元格加到行里,再把行加到表格里 row.appendChild(codeCell); row.appendChild(reasonCell); table.appendChild(row); });
如果非要用你原来的硬编码行
要是你就想沿用现在写的那一行(只能显示第一条数据),那可以这样取值:
<tr id="lender1"> <td id="lender1"><script>document.getElementById("lender1").textContent = declines[0][0];</script></td> <td id="declineReason1"><script>document.getElementById("declineReason1").textContent = declines[0][1];</script></td> </tr>
不过还是推荐动态生成的方式,扩展性强很多。
为啥别用正则处理JSON?
正则适合处理简单的字符串匹配,但JSON有嵌套结构、转义字符等复杂情况,用正则很容易出bug,比如如果拒绝原因里有引号或者特殊字符,正则就会失效。用JSON.parse()是最稳定可靠的方法。
内容的提问来源于stack exchange,提问作者Steve_G
相关产品推荐
相关产品推荐

