Modify multiple json files

Question:

I have a folder with 2000 json files and I have to edit specific line with number based on file name.

files names :-

1.json
2.json
3.json
...
1999.json
2000.json

each file contain text like below:-

1.json

{
    "Name": "Testname #5",
    "Description":
}

2.json

{
    "Name": "Testname #5",
    "Description":
}

Currently no is not in correct order. I want to make like this :

1.json

{
    "Name": "Testname #1",
    "Description":
}

2.json

{
    "Name": "Testname #2",
    "Description":
}

100.json

{
    "Name": "Testname #100",
    "Description":
}

I have done something like this

import os
import sys
import fileinput    

x = 0;
for line in fileinput.input(['1.json'], inplace=True):
    if line.strip().startswith('"name"'):
        line = '"name":"Testname #' + str(x) + '",n'
        x += 1
    sys.stdout.write(line)

this is works for 1 file at a time. I need to do bulk edit. can anyone help me

Asked By: Shankar S Bavan

||

Answers:

You can add your code to a loop that changes the name of the file for every turn like

import json

file_no = int(input('Enter number of files to edit: '))
y = None

for x in range(1, file_no + 1):
    file_name = str(x) + '.json'
    with open(file_name, 'r') as f:
        data = json.load(f)
        for j in data:
            if j.lower() == 'name':
                data[j] = f"Testname #{x}"
                y = data
                break
    
    with open(file_name, 'w') as g:
        json.dump(y, g, indent=4)

This will go for as many files as the number entered.

Answered By: EliteGamerSiddhu

I Think you’ll have to open one file after the other. I don’t see any other way.

for file_name in list_of_filenames:
    with open(file_name) as file:
        # read file
Answered By: Jon_Kle

If they are valid JSON files use the json parser:

import json

for i in range(1, 2001):
    with open(f'{i}.json', 'r+', encoding='utf8') as f:
        data = json.load(f)
        data['Name'] = f'Testname #{i}'
        f.seek(0)                     # rewind
        f.truncate()                  # delete old content
        json.dump(data, f, indent=4)  # write new content
Answered By: Mark Tolonen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.