'Saving data to a json file using python

I have JSON data stored in a file (Movies.json). i want to read the file and do some process and then save the output in new file

with open("Movies.json",'r') as f:
        movies = json.loads(f.read())
        // doing some process

How can i save the output?

Currently, I am trying this but it's not working:

json.dump(movies, f)


Solution 1:[1]

for output you need to use 'w' instead of 'r'

import json 
# Opening JSON file
f = open('movies.json')

# returns JSON object as
# a dictionary
movies = json.load(f)

# Iterating through the json
# list
for i in movies:
    print(i['id'])
 
# output 
with open("Movies.json", 'w') as f:
    json.dump(movies, f)
    
# Closing file
f.close()

Solution 2:[2]

You are using 'r' it is for reading, you should use 'w'

import json 
with open("Movies.json", 'w') as f:
    json.dump(movies, f)

Solution 3:[3]

You need to let the file be closed and then reopen it for write and write the modified object back again:

with open("Movies.json", 'w') as f:
    json.dump(movies, f)

Solution 4:[4]

with open("Movies.json",'r') as rf:
    with open("New_Movies.json",'w') as wf:
          movies = json.loads(rf.read())
          #doing some process
          movies_after_process = do_something(movies)
          wf.write(json.dumps(movies_after_process))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Akash Singh
Solution 2 umutkedik
Solution 3 quamrana
Solution 4 Jonatrios