如何使用javascript解码json循环数据



我从事包跟踪API,它在json 中返回数据

我正在使用javascript输出数据

前三个输出是完美的,但问题是"current_ status";以及";"状态";有缩进/嵌套的数据,如何输出?

const data = {
"packet_id": "0024-00003711",
"consignee_name": "Nasir maqbool",
"destination": "Lahore",
"current_status": {
"status": "Assigned to Courier",
"datetime": "2020-12-27T17:55:05.414Z",
"comment": null
},
"statuses": [{
"status": "Pickup request sent",
"datetime": "2020-12-27T09:55:41.295Z",
"comment": null
}, {
"status": "Booked",
"datetime": "2020-12-26T10:13:15.333Z",
"comment": null
}]
}
let html = "";
html += '<div><strong>Packet Id:</strong> ' + data.packet_id + '</div>';
html += '<div><strong>Consignee Name:</strong> ' + data.consignee_name + '</div>';
html += '<div><strong>Destination:</strong> ' + data.destination + '</div>';
html += '<div><strong>Current Status:</strong>???</div>';
html += '<div><strong>Status:</strong> ???</div>';
$("#response").html(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="response"></div>

您可以映射

const data = { "packet_id": "0024-00003711", "consignee_name": "Nasir maqbool", "destination": "Lahore", "current_status": { "status": "Assigned to Courier", "datetime": "2020-12-27T17:55:05.414Z", "comment": null }, "statuses": [{ "status": "Pickup request sent", "datetime": "2020-12-27T09:55:41.295Z", "comment": null }, { "status": "Booked", "datetime": "2020-12-26T10:13:15.333Z", "comment": null }] };

const curStatus = Object.entries(data.current_status)
.map(entr => `<li>${entr[0]}:${entr[1]}</li>`) // map the entries 
.join("") // join

const statuses = data.statuses
.map(ent => Object.entries(ent) // map each status
.map(entr => `<li>${entr[0]}:${entr[1]}</li>`) // map the entries in the statuses
.join("") // join
).join("</ul><hr><ul>") // join with a separator

const html = `<div><strong>Packet Id:</strong>${data.packet_id}</div>
<div><strong>Consignee Name:</strong>${data.consignee_name}</div>
<div><strong>Destination:</strong>${data.destination}</div>
<div><strong>Current Status:</strong><ul>${curStatus}</ul></div>
<div><strong>Previous statuses:</strong><ul>${statuses}</ul></div>`
$("#response").html(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="response"></div>

最新更新