如何基于指定字符串列表移除JSON中的列表项?
基于指定字符串列表移除JSON中的列表项解决方案
问题场景
给定如下JSON结构:
{ "test": [{ "Location": "Singapore", "Values": [{ "Name": "00", "subvalues": [ "5782115e1", "688ddd16e", "3e91dc966", "5add96256", "10352cf0f", "17f233d31", "130c09135", "2f49eb2a6", "2ae1ad9e0", "23fd76115" ] }, { "Name": "01", "subvalues": [ "b43678dfe", "202c7f508", "73afcaf7c" ] } ] }] }
需要移除的字符串列表:["130c09135", "2f49eb2a6", "5782115e1", "b43678dfe"],最终得到过滤后的合法JSON结构。
解决方案
直接文本替换极易破坏JSON格式(比如引号、逗号错位),必须通过解析JSON为可操作的数据结构,处理后再重新生成合法JSON。下面提供两种方案,适合不同需求:
方案1:Python代码实现(新手友好)
Python自带的json库可以轻松完成解析、修改、序列化全流程,代码逻辑清晰:
import json # 1. 用集合存储待移除字符串(查询效率比列表高) remove_set = {"130c09135", "2f49eb2a6", "5782115e1", "b43678dfe"} # 2. 读取并解析JSON文件(如果是JSON字符串,改用json.loads()) with open("input.json", "r", encoding="utf-8") as f: json_data = json.load(f) # 3. 遍历目标层级,过滤subvalues列表 for value_item in json_data["test"][0]["Values"]: # 保留不在移除集合中的元素 value_item["subvalues"] = [val for val in value_item["subvalues"] if val not in remove_set] # 4. 将处理后的数据写入新文件,indent参数保证格式化输出 with open("output.json", "w", encoding="utf-8") as f: json.dump(json_data, f, indent=4)
执行后,output.json会生成你期望的结果:
{ "test": [{ "Location": "Singapore", "Values": [{ "Name": "00", "subvalues": [ "688ddd16e", "3e91dc966", "5add96256", "10352cf0f", "17f233d31", "2ae1ad9e0", "23fd76115" ] }, { "Name": "01", "subvalues": [ "202c7f508", "73afcaf7c" ] } ] }] }
方案2:命令行工具jq(无需写代码)
如果你熟悉命令行,用jq工具可以快速完成操作:
# 直接在命令行指定待移除字符串 jq '.test[0].Values[] | .subvalues |= [.[] | select(. != "130c09135" and . != "2f49eb2a6" and . != "5782115e1" and . != "b43678dfe")]' input.json > output.json
如果待移除字符串较多,可以把它们存到remove.txt(每行一个字符串),再执行:
jq --argfile remove remove.txt '.test[0].Values[] | .subvalues |= [.[] | select(IN($remove[]; .) | not)]' input.json > output.json
内容的提问来源于stack exchange,提问作者Knight
相关产品推荐
相关产品推荐

