繁体   English   中英

如何在 W3 JS 中解析 JSON 对象

[英]How to parse JSON object in W3 JS

我从 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 不是数组。

此代码不起作用。

在您的 JSON 中,订单是一个包含order数组的对象,

<tbody w3-repeat="o in c.orders">

所以你必须在订单中引用订单数组

<tbody w3-repeat="o in c.orders.order">

c.orders确实不是数组,但c.orders.order是数组。 迭代它,它会起作用。

专业提示:下次只需查看错误,它可能会告诉您究竟出了什么问题...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM