1

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!

4
  • Why are using 2 seperate loops rather than 1 common loop? Commented Apr 26, 2021 at 9:45
  • Thank you very much! That was easier than I had expected! I found another mistake: the "with open(filename, 'w') as f:" statement has to be within the loop. But thanks, now everything is working as it should :) Commented Apr 26, 2021 at 9:49
  • Instead of doing basename[-9:] == '.min.json': name = basename[0:-9], I think you could have created a suffix variable (suffix = ".min.json"), and then, used this variable to do the other 2 operations, such as... if basename.endswith(suffix): name = basename[0:len(suffix)]. That way, you only need to change the suffix variable, and your program would still work as intended. :) Commented Apr 26, 2021 at 9:52
  • Thanks for the good tip! :) Commented Apr 26, 2021 at 9:57

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.