使用python删除json文件中指定的key值

本文介绍如何使用Python脚本从JSON文件中删除由另一文件指定的键值。通过将JSON文件转化为字典,然后遍历并删除与指定文件中键相匹配的值,最终更新回JSON文件。内容涵盖了从字符串到字典的转换方法,以及在处理过程中可能遇到的TypeError问题和基础Python知识链接。

问题:有1个文件t1.txt数据格式是json。

有另外1个文件t2.txt是key1111,key2222。把对应在t1.txt中的值删掉,有什么好办法么?

思路1:1条shell命令

cat t1.txt | python -c 'import sys,json; a=json.load(sys.stdin);del a["jobs"]["1111"];del a["jobs"]["2222"];print a'
cat t1.txt | python -m json.tool >> t2.txt
sed '/1111\|2222/,+3d' t2.txt

 

思路2:用python脚本删,把t1赋给1个字典型的变量,把t2给一个list变量,循环读取变量元素作为key,直接删除t1对应的值。
主要是string转换为dict或者json文件直接转换为dict。

1)# 使用json模块直接把文件转换为字典值
#https://docs.python.org/3/library/json.html

#!/usr/bin/env python
import json
def convertDict():
    with open('t1.txt') as json_file:
        data = json.load(json_file)
        return data
        
if __name__ == "__main__":
    fileToDict = convertDict()
    keyList = ["key1111","key2222"]
    for k in keyList:
        del fileToDict["jobs"][k]
    print json.dumps(fileToDict)

 

2)# 因为这是个linux下的配置文件,可以使用commands模块call shell command取值。
#http://stackoverflow.com/questions/988228/convert-a-string-representation-of-a-dictionary-to-a-dictionary
#convert string to dictionay by
#ast.literal_eval or json.loads()

#!/usr/bin/env python
import commands
import json
def convertDict():
    outStr = commands.getoutput("cat t1.txt  | python -m json.tool")
    json_acceptable_string = outStr.replace("'", "\"")
    toDict = json.loads(json_acceptable_string)
    print type(toDict)
    print toDict
    return toDict

if __name__ == "__main__":
    fileToDict = convertDict()
    keyList = ["1111","2222"]
    for k in keyList:
        del fileToDict["jobs"][k]

    print json.dumps(toDict)

 

3)# other ways for covert string to dictionay

#http://leaya00.iteye.com/blog/853366

#!/usr/bin/env python
import commands
import json
def convertDict():
    outStr = commands.getoutput("cat t1.txt | python -m json.tool")
    toDict = eval(outStr)
    #exec("toDict=" + outStr)
    print type(toDict)
    print toDict
    return toDict
if __name__ == "__main__":
    fileToDict = convertDict()
    keyList = ["1111","2222"]
    for k in keyList:
        del fileToDict["jobs"][k]
    print json.dumps(fileToDict)

4)遇到的错误TypeError: string indices must be integers, not str
http://stackoverflow.com/questions/15388980/typeerror-string-indices-must-be-integers-not-str
主要是使用commands.getoutput()获取shell命令的输出值是个string,不能直接当作dict来处理。

5)一些基础的python知识参考
http://www.runoob.com/python/python-dictionary.html
http://www.jb51.net/article/47978.htm list
http://www.jb51.net/article/47990.htm dictionary
https://docs.python.org/3/library/json.html

转载于:https://www.cnblogs.com/gracejiang/p/6398703.html

Python中,可使用`json`模块和字典操作来删除JSON文件中的指定内容。对于简单的JSON结构,可直接将文件内容加载为字典,然后删除指定的键对;对于嵌套较深的JSON数据,递归函数能更高效地完成任务[^1]。 ### 简单JSON结构的处理 对于简单的JSON文件,可按以下步骤操作: ```python import json # 打开并加载JSON文件 with open('example.json', 'r', encoding='utf-8') as file: data = json.load(file) # 删除指定内容,假设要删除键为 'key_to_delete' 的内容 if 'key_to_delete' in data: del data['key_to_delete'] # 将修改后的数据写回文件 with open('example.json', 'w', encoding='utf-8') as file: json.dump(data, file, indent=4) ``` 上述代码先将JSON文件内容加载到字典`data`中,接着检查要删除的键是否存在,若存在则删除该键对,最后将修改后的数据写回文件。 ### 嵌套JSON结构的处理 对于嵌套的JSON数据,可使用递归函数来删除指定内容: ```python import json def remove_key(data, key_to_remove): if isinstance(data, dict): return {k: remove_key(v, key_to_remove) for k, v in data.items() if k != key_to_remove} elif isinstance(data, list): return [remove_key(item, key_to_remove) for item in data] return data # 打开并加载JSON文件 with open('nested_example.json', 'r', encoding='utf-8') as file: data = json.load(file) # 删除指定内容 key_to_remove = 'nested_key_to_delete' data = remove_key(data, key_to_remove) # 将修改后的数据写回文件 with open('nested_example.json', 'w', encoding='utf-8') as file: json.dump(data, file, indent=4) ``` 此代码定义了一个递归函数`remove_key`,用于遍历JSON数据中的所有嵌套层级,删除指定的键对。 ### 使用命令行结合Python代码处理 也可在命令行中使用Python代码直接对JSON数据进行处理: ```bash cat example.json | python -c 'import sys,json; a=json.load(sys.stdin);del a["key_to_delete"];print(json.dumps(a, indent=4))' > new_example.json ``` 该命令将`example.json`文件的内容通过管道传递给Python代码,Python代码将标准输入的内容加载为JSON数据,然后删除指定的键,最后将处理后的JSON数据输出到`new_example.json`文件中[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值