To work with JSON data and files in Python, you use the json
module. It has methods for:
load
-ing JSON data from files and converting them to Python objects
dump
-ing Python objects to files in JSON format
In Python, JSON is represented as a regular dictionary, so you simply have to read the string from the file, turn it into a dictionary, add any other key-value pairs you want or even modify the data, then dump
it back to the file.
Now since you only want to do this conversion if the file contains only a string, you can first do json.load
, then use isinstance
to check if it was converted to a dictionary. If yes, then it's already in proper JSON so you don't have to do anything. If no, and it was converted to a string, then continue with the processing.
Lastly, since you want to overwrite the same file, open the file in "r+"
mode for reading and writing.
import json
# Assume script and files are in the same directory
filepaths = [
"File1.json", # Contains "I\nhave\na\ncat"
"File2.json", # Contains "I\nhave\na\ndream"
"File3.json", # Correct JSON
]
# Process each file one-by-one
for file_id, filepath in enumerate(filepaths):
with open(filepath, "r+") as f:
contents = json.load(f)
if isinstance(contents, dict):
# This is already in JSON, nothing to fix
continue
# We need to fix the file
data = {"id": file_id, "string": contents}
f.seek(0)
json.dump(data, f)