如何移除嵌套对象中available为false的components子对象?
过滤JSON中键值对对象里的指定条目
你需要处理嵌套JSON里product.components这个键值对对象,移除其中所有available属性为false的子对象,同时保留原JSON结构不变。下面提供两种主流编程语言的实现方案:
JavaScript 实现
通过遍历components的所有键,判断子对象的available值,仅保留符合条件的条目:
// 假设原始JSON已解析为对象 const data = { "msg": "OK", "blueprint": { "result": "OK", "blueprint": { "id": "a2e63ee01401aaeca78be023dfbb8c59", "product": { "productName": "Test Product", "productId": "AS_12-01", "description": "Test Descr.", "childProducts": [ {"childId": "T1", "parent": "8c59"}, {"childId": "T5", "parent": "8c7e"} ], "components": { "component1": {"compId": "C2", "leadTime": 21, "available": false}, "component2": {"compId": "C5", "leadTime": 3, "available": true}, "component3": {"compId": "C6", "leadTime": 12, "available": false}, "component4": {"compId": "C8", "leadTime": 5, "available": true} } }, "owner": "dummy", "name": "du_test" } } }; // 过滤components对象 const filteredComponents = {}; for (const key in data.blueprint.blueprint.product.components) { const component = data.blueprint.blueprint.product.components[key]; if (component.available) { filteredComponents[key] = component; } } // 替换原对象的components字段 data.blueprint.blueprint.product.components = filteredComponents; // 输出处理后的结果 console.log(JSON.stringify(data, null, 2));
Python 实现
用字典推导式快速筛选符合条件的键值对,直接替换原字段:
import json # 原始JSON字符串 json_str = '''{ "msg": "OK", "blueprint": { "result": "OK", "blueprint": { "id": "a2e63ee01401aaeca78be023dfbb8c59", "product": { "productName": "Test Product", "productId": "AS_12-01", "description": "Test Descr.", "childProducts": [ {"childId": "T1", "parent": "8c59"}, {"childId": "T5", "parent": "8c7e"} ], "components": { "component1": {"compId": "C2", "leadTime": 21, "available": false}, "component2": {"compId": "C5", "leadTime": 3, "available": true}, "component3": {"compId": "C6", "leadTime": 12, "available": false}, "component4": {"compId": "C8", "leadTime": 5, "available": true} } }, "owner": "dummy", "name": "du_test" } } }''' # 解析JSON为字典 data = json.loads(json_str) # 过滤components:仅保留available为True的条目 data['blueprint']['blueprint']['product']['components'] = { key: comp for key, comp in data['blueprint']['blueprint']['product']['components'].items() if comp['available'] } # 输出处理后的结果 print(json.dumps(data, indent=2))
内容的提问来源于stack exchange,提问作者AbreQueVoy
相关产品推荐
相关产品推荐

