Clara
Clara

Reputation: 49

Iterating through and updating JSON files in Python

I have a directory with JSON files that all have the same structure. I would like to loop through them and replace the values of key 'imgName' with the basename of the filename + 'png'. I managed to do that, however, when I dump the content of my dictionaries in the JSON files, they are empty. I'm sure there is some problem with the logic of my loops, but I can't figure it out.

Here is my code:

distorted_json = glob.glob('...')

for filename in distorted_json:
    with open(filename) as f:
        json_content = json.load(f)
        basename = os.path.basename(filename)
        if basename[-9:] == '.min.json':
            name = basename[0:-9]
            for basename in json_content:
                json_content['imgName'] = name + '.png'

for filename in distorted_json:
    with open(filename, 'w') as f:
        json.dumps(json_content)

Thank you very much in advance for any advice!

Upvotes: 1

Views: 305

Answers (1)

python_user
python_user

Reputation: 7083

You need to use json.dump, that is used to dump to a file, json.dump(json_content, f). Also remove the second loop and move the contents to the previous loop.

for filename in distorted_json:
    with open(filename) as f:
        json_content = json.load(f)
        basename = os.path.basename(filename)
        if basename[-9:] == '.min.json':
            name = basename[0:-9]
            for basename in json_content:
                json_content['imgName'] = name + '.png'
                
    with open(filename, 'w') as f:
        json.dump(json_content, f)

Upvotes: 1

Related Questions