javascript - 如何使用 javascript 解码 json 循环数据
问题描述
我正在使用包裹跟踪 API,它以 json 格式返回数据
我正在使用 javascript 来输出数据
前三个输出是完美的,但问题是“current_status”和“statuses”有缩进/嵌套数据,如何输出它们?
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>
推荐阅读
- java - 如何使用 PdfBox 删除可选内容组 (OCG)
- python - 在逻辑函数的 MLE 估计中,在牛顿拉夫森的实现中反复出现“奇异矩阵”的错误
- r - 如何将未定义数量的ggplot项目放入网格中
- java - 将 Collection 与 ReplyingKafkaTemplate 一起使用时,相关 ID 丢失
- python-3.x - 如何为大量文本创建字典并列出最常用的单词?
- go - 尝试重新创建 Web 服务的模拟版本
- javascript - 使用 iframe 嵌入有哪些陷阱
- redis - Redis 缓存包含 200 万行的表
- python - 设置要在线程完成时执行的行为
- java - 杰克逊反序列化字符串失败