javascript如何在W3 JS中解析JSON对象
我从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、 订单不是数组
此代码不起作用
# 1 楼答案
在JSON中,orders是一个包含
order
数组的对象因此,必须在orders中引用order数组
# 2 楼答案
c.orders
确实不是数组,但c.orders.order
是数组。迭代一下,它就会工作专业提示:下次只要看看错误,它可能会告诉你到底是什么错了