About how the python json file inside a plurality of data deleted, leaving only the entry they need

Reference blog:

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

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

How to meet the conditions of entry section json1 file is extracted? That is, you do not need to delete the entry.

I'm using one of the most awkward way is to put the data in a file json1 strip line json converted for viewing as a dictionary, if the condition is saved as a file json2 inside.

1, load json library:

 1 import json 

2, open the file for reading json1:

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

3, json2 open the file for writing:

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

4, according to the line that reads json1 file:

 4 for jsonLine in aminerFile: 

5, the format is converted into a string dictionary format:

 5 lwPythonLine = json.loads(jsonLine) 

6, it is determined whether the current row satisfies the condition we require (I here is to determine whether there are 'r' attribute of the current row, and 'r' value is not less than the length dimension 20 is saved, the other discarded):

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

7, if the condition is satisfied then the current row is written to a file json2, while the subsequent insertion of line breaks in json2 file, the json data is stored one by one, rather than a large group:

7     json.dump(lwPythonLine, jsonFile)
8     jsonFile.write('\n')

 

It is complete, all of the code:

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')

A warm welcome criticism correction!

 

Guess you like

Origin www.cnblogs.com/duna1160288954/p/11571587.html