如何访问JSON中父键动态变化的嵌套对象并生成HTML表格
动态嵌套键的JSON数据提取与表格生成
问题说明
发起JSON请求后需访问特定嵌套对象,但部分父级键为动态变化值。示例JSON数据如下:
{ "ID": 752357, "name": "John Doe", "age": 25, "status": {}, "detail": { "level": 12, "attack": "5", "def": "10" }, "item": { "890099870": { "bag": { "12345": { "name": "Bones", "quantity": 338, "status": 0 }, "45678": { "name": "Iron Ores", "quantity": 99, "status": 0 } }, "expire": { "start": 1692288000, "end": 0 } } } }
其中item下的键(如"890099870")会随服务器数据更新动态变化,物品ID(如"12345"、"45678")也会随库存内容改变。需要提取库存物品的ID、名称和数量,生成如下格式的表格:
| ID | Name | Quantity |
|---|---|---|
| 12345 | Bones | 338 |
| 45678 | Iron Ores | 99 |
解决方法
核心思路
通过遍历对象的动态键,跳过硬编码固定键的方式,直接获取目标嵌套数据,再提取所需字段生成表格。
JavaScript实现示例
// 假设response是请求返回的JSON对象 const itemGroup = response.item; // 获取item下的动态键(若存在多个动态键,可循环遍历所有键) const dynamicItemKey = Object.keys(itemGroup)[0]; const bagItems = itemGroup[dynamicItemKey].bag; // 提取物品信息 const itemList = Object.entries(bagItems).map(([id, itemInfo]) => ({ id, name: itemInfo.name, quantity: itemInfo.quantity })); // 生成HTML表格 let tableHtml = `<table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Quantity</th> </tr> </thead> <tbody>`; itemList.forEach(item => { tableHtml += ` <tr> <td>${item.id}</td> <td>${item.name}</td> <td>${item.quantity}</td> </tr>`; }); tableHtml += ` </tbody> </table>`; console.log(tableHtml);
Python实现示例
# 假设json_data是解析后的JSON字典 json_data = { "ID": 752357, "name": "John Doe", "age": 25, "status": {}, "detail": { "level": 12, "attack": "5", "def": "10" }, "item": { "890099870": { "bag": { "12345": { "name": "Bones", "quantity": 338, "status": 0 }, "45678": { "name": "Iron Ores", "quantity": 99, "status": 0 } }, "expire": { "start": 1692288000, "end": 0 } } } } # 获取动态键对应的背包数据 dynamic_key = next(iter(json_data['item'].keys())) bag_data = json_data['item'][dynamic_key]['bag'] # 生成目标格式表格 print("| ID | Name | Quantity |") print("| -------- | -------- | -------- |") for item_id, info in bag_data.items(): print(f"| {item_id:<8} | {info['name']:<8} | {info['quantity']:<8} |")
内容的提问来源于stack exchange,提问作者Zin Lwin
相关产品推荐
相关产品推荐

