如何在 W3 JS 中解析 JSON 对象
Posted
技术标签:
【中文标题】如何在 W3 JS 中解析 JSON 对象【英文标题】:How to parse JSON object in W3 JS 【发布时间】:2020-04-11 21:50:52 【问题描述】:我从 Spring boot Restful api 获得的 Json 对象。
"customers":["customerId":1,"country":"United States","orders":"order":["shipCountry":"France","orderId":10248,"freight":32.38,"shipCountry":"Japan","orderId":10249,"freight":12.43,"shipCountry":"Russia","orderId":10250,"freight":66.35],"name":"John Hammond","customerId":2,"country":"India","orders":"order":["shipCountry":"Argentina","orderId":10266,"freight":77.0,"shipCountry":"Australia","orderId":10267,"freight":101.12,"shipCountry":"Germany","orderId":10268,"freight":11.61],"name":"Mudassar Khan","customerId":3,"country":"France","orders":"order":["shipCountry":"Brazil","orderId":10250,"freight":65.83],"name":"Suzanne Mathews","customerId":4,"country":"Russia","orders":"order":["shipCountry":"Belgium","orderId":10233,"freight":89.11,"shipCountry":"Canada","orderId":10234,"freight":51.3,"shipCountry":"Austria","orderId":10235,"freight":46.11],"name":"Robert Schidner"]
html 和 W3Js 代码如下。
<!DOCTYPE html>
<html>
<title>W3.JS</title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="https://www.w3schools.com/lib/w3.js"></script>
<body class="w3-container">
<table id="id01" class="w3-table-all">
<tr>
<th>Customer Id</th>
<th>Name</th>
<th>Country</th>
<th>Orders</th>
</tr>
<tbody w3-repeat="c in customers">
<tr>
<td>c.customerId</td>
<td>c.name</td>
<td>c.country</td>
<td>
<table class="w3-table-all">
<tr>
<th>Order Id</th>
<th>Freight</th>
<th>ShipCountry</th>
</tr>
<tbody w3-repeat="o in c.orders">
<tr>
<td>o.orderId</td>
<td>o.freight</td>
<td>o.ShipCountry</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<script>
w3.getHttpObject('http://localhost:8080/customers/all', myFunction);
function myFunction(myObject)
w3.displayObject("id01", myObject);
</script>
</body>
</html>
错误信息:w3-repeat 必须是一个数组。 c.orders 不是数组。
此代码无效。
【问题讨论】:
【参考方案1】:在您的 JSON 中,orders 是一个包含 order
数组的对象,
<tbody w3-repeat="o in c.orders">
所以你必须引用订单里面的订单数组
<tbody w3-repeat="o in c.orders.order">
【讨论】:
【参考方案2】:c.orders
确实不是数组,但c.orders.order
是数组。对此进行迭代,它会起作用。
专业提示:下次只需查看错误,它可能会告诉您确切的问题...
【讨论】:
我觉得有错别字,应该是c.orders.order
。以上是关于如何在 W3 JS 中解析 JSON 对象的主要内容,如果未能解决你的问题,请参考以下文章