如何使用Ruby移除JSON对象中的多个passthrough_fields字段
如何移除JSON中所有的
passthrough_fields字段并保存到新变量? 我的JSON示例如下,希望移除所有
passthrough_fields字段并保存到新变量:{ "type": "playable_item", "id": "p06s0lq7", "urn": "urn:bbc:radio:episode:p06s0mk3", "network": { "id": "bbc_radio_five_live", "key": "5live", "short_title": "Radio 5 live", "logo_url": "https://sounds.files.bbci.co.uk/v2/networks/bbc_radio_five_live/{type}_{size}.{format}", "passthrough_fields": {} }, "titles": { "primary": "Replay", "secondary": "Bill Shankly", "tertiary": null, "passthrough_fields": {} }, "synopses": { "short": "Bill Shankly with Sue MacGregor in 1979 - five years after he resigned as Liverpool boss.", "medium": null, "long": "Bill Shankly in conversation with Sue MacGregor in 1979, five years after he resigned as Liverpool manager.", "passthrough_fields": {} }, "image_url": "https://ichef.bbci.co.uk/images/ic/{recipe}/p06qbz1x.jpg", "duration": { "value": 1774, "label": "29 mins", "passthrough_fields": {} }, "progress": null, "container": { "type": "series", "id": "p06qbzmj", "urn": "urn:bbc:radio:series:p06qbzmj", "title": "Replay", "synopses": { "short": "Colin Murray unearths classic sports commentaries and interviews from the BBC archives.", "medium": "Colin Murray looks back at 90 years of sport on the BBC by unearthing classic commentaries and interviews from the BBC archives.", "long": null, "passthrough_fields": {} }, "activities": [], "passthrough_fields": {} }, "availability": { "from": "2018-11-16T16:18:54Z", "to": null, "label": "Available for over a year", "passthrough_fields": {} }, "guidance": { "competition_warning": false, "warnings": null, "passthrough_fields": {} }, "activities": [], "uris": [ { "type": "latest", "label": "Latest", "uri": "/v2/programmes/playable?container=p06qbzmj&sort=sequential&type=episode", "passthrough_fields": {} } ], "passthrough_fields": {} }
当然可以搞定!要移除JSON里所有层级的passthrough_fields字段,关键是要递归遍历整个JSON结构——因为这个字段可能出现在顶层、嵌套对象甚至数组元素里。下面给你两种最常用的实现方案:
方案1:JavaScript 实现
在前端或Node.js环境中,直接操作JSON对应的对象/数组即可,用递归函数处理所有嵌套层级:
// 原始JSON对象 const originalJson = { /* 这里放入你的原始JSON对象 */ }; // 递归移除指定字段的函数 function removePassthroughFields(obj) { if (Array.isArray(obj)) { // 处理数组:遍历每个元素并递归处理 return obj.map(item => removePassthroughFields(item)); } else if (typeof obj === 'object' && obj !== null) { // 处理对象:过滤掉目标字段,同时递归处理每个值 return Object.fromEntries( Object.entries(obj) .filter(([key]) => key !== 'passthrough_fields') .map(([key, value]) => [key, removePassthroughFields(value)]) ); } // 非对象/数组类型直接返回(比如字符串、数字、null) return obj; } // 生成清理后的新对象 const cleanedJson = removePassthroughFields(originalJson); console.log(cleanedJson);
这个函数会完整遍历所有嵌套结构,确保每一层的passthrough_fields都被移除,而且不会修改原始对象,完全返回一个新的结构。
方案2:Python 实现
如果是后端处理,Python的字典和列表操作同样适合用递归解决:
import json # 读取原始JSON(如果是文件的话,用json.load()读取) original_json_str = '''/* 这里放入你的原始JSON字符串 */''' original_data = json.loads(original_json_str) def remove_passthrough_fields(data): if isinstance(data, dict): # 处理字典:过滤目标字段,递归处理每个值 return { key: remove_passthrough_fields(value) for key, value in data.items() if key != 'passthrough_fields' } elif isinstance(data, list): # 处理列表:递归处理每个元素 return [remove_passthrough_fields(item) for item in data] else: # 非容器类型直接返回 return data # 生成清理后的数据 cleaned_data = remove_passthrough_fields(original_data) # 如果需要保存到新文件 with open('cleaned_output.json', 'w', encoding='utf-8') as f: json.dump(cleaned_data, f, indent=2, ensure_ascii=False) print(cleaned_data)
这段代码会处理所有嵌套的字典和列表,移除所有passthrough_fields字段,最后可以直接把清理后的数据转成JSON字符串或保存到文件。
内容的提问来源于stack exchange,提问作者Nipun Tanay
相关产品推荐
相关产品推荐

