python 关于如何把json文件里面的多条数据删除,只保留自己需要的条目

2022-10-15,,,,

参考博客:

https://www.cnblogs.com/bigberg/p/6430095.html

https://zhidao.baidu.com/question/717320833852811685.html

如何把json1文件中的部分满足条件的条目提取出来?也就是删除自己不需要的条目。

我使用的是一个最笨拙的方法,就是把json1文件中的数据一条条json行转化为字典进行查看,如果满足条件则另存成一个json2文件里面。

1、加载json库:

 1 import json 

2、打开json1文件用于读取:

 2 aminerfile = open(r'...\json1.txt','r') 

3、打开json2文件用于写入:

 3 with open(r'...\json2.txt','w') as jsonfile: 

4、按行读取json1文件:

 4 for jsonline in aminerfile: 

5、字符串格式转化成字典格式:

 5 lwpythonline = json.loads(jsonline) 

6、判断当前行是否满足我们所要求的条件(我这边是判断当前行中是否有’r‘属性,且’r‘值的长度不能低于20维则保存,其他的丢弃):

 6 if ('r' in lwpythonline) and len(lwpythonline['r']) >= 20: 

7、如果满足条件则将当前行写入到json2文件中,同时随后在json2文件中插入换行符,是的json数据一条一条的存放,而不是一个大段:

7     json.dump(lwpythonline, jsonfile)
8     jsonfile.write('\n')

 

就完成了,代码全部为:

import json
aminerfile = open(r'...\json1.txt','r')
with open(r'...\json2.txt','w') as jsonfile:
    for jsonline in aminerfile:
        lwpythonline = json.loads(jsonline)
        if ('r' in lwpythonline) and len(lwpythonline['r']) >= 20:
            json.dump(lwpythonline, jsonfile)
            jsonfile.write('\n')

热烈欢迎批评指正!

 

《python 关于如何把json文件里面的多条数据删除,只保留自己需要的条目.doc》

下载本文的Word格式文档,以方便收藏与打印。