Skip to content Skip to sidebar Skip to footer

Python - Deleting Lines Of Code In Json File

I would like to search and replace multiple lines of code a JSON file with nothing except the first one that will use the users input but I cant get it to work I would like to sear

Solution 1:

It's a little complicated. Your JSON file format contains many <list> data (according to Python interpretation). I wrote you a quick and simple solution - see the source code below. However, it would like to improve the code for the custom parser, or to improve the transformation from JSON to Python and vice versa. You could also truncate the OOP code into a single row like: data = json.loads(open('/tmp/a.json','r').read()). But you wrote that you are still new to Python. So on multiple lines it's better for understanding. Test over the Python console, otherwise you must paste all variables into print().

import json

### read json data from file
#with open('/tmp/a.json') as f:
#    data = json.load(f)

### read text from file
with open('/tmp/a.json','r') as f:
    data = f.read()

### decode JSON data
data = json.loads(data)

print('- check before:')
data['tabs'][0]['views'][1]['screenshots']

print('- Now we\'re going to overwrite the whole frame with "screenshots" for one, the first one that\'s already there. So there will only be the first record, i.e. "Screenshot URL 1" as you like.')
data['tabs'][0]['views'][1]['screenshots']  =  data['tabs'][0]['views'][1]['screenshots'][0] 

print('- check after:')
data['tabs'][0]['views'][1]['screenshots']

### write encoded JSON data to output file
### warning - the tree structure will be deleted (all newlines), but the JSON format should remain original
with open('/tmp/b.json','w') as f:
    f.write(json.dumps(data))

Post a Comment for "Python - Deleting Lines Of Code In Json File"