Creating a new JSON file from an existing JSON file

Question:
I am trying to create a new file from an existing json file(duplicate the content of JsonFile1 onto JsonFile2) but my duplicate file JsonFile2 is empty.
Repl link:
https://replit.com/@jonathanessombe/new-attempt#main.py

import json

with open('Json_file1.json', 'r') as JsonFile1:
  JasonToPython = json.load(JsonFile1)
  print(JasonToPython)

with open('Json_file2.json', 'w') as JsonFile2:
  json.dumps(JasonToPython)

#Json_file1.json
{           "name":"Mercy", 
            "age":16,
            "average": 89.9,
            "drivers_licence": null,
            "failing?": false
}







1 Like

The json.dumps function does not write to the .json file, converts the dictionary to a string (the inverse of the json.load function).

Having received a string with data, you do nothing with it, do not write to a file and do not display it on the screen, so nothing happens with this string.

To write a string to a .json file, you need to use the write function to which you are feeding the string (you got this string using the json.dumps function).

Then your entry code will look like this:

with open('Json_file2.json', 'w') as JsonFile2:
  JsonFile2.write(json.dumps(JasonToPython, indent=4)) # indent specifies the number of indents in the json file
3 Likes

Hey @jonathanessombe, it appears that you’re attempting to duplicate the content of JsonFile1 to JsonFile2, but you’re not writing the JSON data to JsonFile2. You should follow these steps:

import json

# Read data from JsonFile1
with open('Json_file1.json', 'r') as JsonFile1:
    JasonToPython = json.load(JsonFile1)

# Write data to JsonFile2
with open('Json_file2.json', 'w') as JsonFile2:
    json.dump(JasonToPython, JsonFile2)  # Note the change from json.dumps to json.dump

steps? no rather code example.

2 Likes

I tried to type out json.dump() instead of json.dumps() but i get a syntax error when i do that

1 Like
import json

with open('Json_file1.json', 'r') as JsonFile1:
  JasonToPython = json.load(JsonFile1)

with open('Json_file2.json', 'w') as JsonFile2:
  json.dump(JasonToPython, JsonFile2, indent=2, sort_keys=True)
1 Like

Are the 3 backticks ``` intentional?

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.