# CONVERT JSON TO CSV if extension = "json": # get all keys in json objects keys = for i in range(0,len(data)): for j in data: if j not in keys: keys.append(j) This means we need to loop through the entire data set to find all unique keys. In a JSON file, each object is independent of the others meaning it may have keys other objects do not. This is because in a CSV file all your keys are conveniently located in the first row. The general structure of the block is similar, but the sections are a bit more complex. Now to write the section for converting JSON to CSV. Also, notice the outer loop starts at index 1 for the range because the first row contains the keys and not data. We’re nesting loops, so the outer loop uses the variable i while the inner loop uses the variable j. # CONVERT CSV TO JSON if extension = "csv": keys = data converted = for i in range(1, len(data)): obj = OrderedDict() for j in range(0,len(keys)): if len(data) > 0: obj] = data else: obj] = None converted.append(obj) Once all cells for the row have been added to the Ordered Dictionary, add the object to the larger array.Add the key-value pair to the Ordered Dictionary where the key is the text from the first row and the value is either the data if present or None if it’s empty.
Loop through each value (what would be each cell within a spreadsheet).After creating an empty list for all the converted data, the following steps will happen for each of the data-containing rows: Knowing that the first row is the keys, we now need to loop through the remaining rows for the data. The key is the identifier for the value within the object. These column names will become the keys in JSON’s key-value-pair structure. Since a CSV file is tabular, the first row will have the names of each column. The OrderedDict setting will ensure that the properties stay in the order that they are read. Without this setting, the JSON key-value pairs would be orderless, meaning each object’s properties will show in various arrangements. The argument object_pairs_hook=OrderedDict is critical here. try: print("Which file do you want to convert?") filename = input("Filename: ") extension = filename.split(".").lower() f = open(filename) if extension = "csv": # load csv file data = list(csv.reader(f)) print("CSV file loaded") elif extension = "json": # load json file data = json.load(f, object_pairs_hook=OrderedDict) print("JSON file loaded") else: print("unsupported file type. Afterwards, we’ll use the appropriate method to read in the file- csv.reader() or json.load()-while printing an error message and exiting if the file does not have the appropriate extension.
We use the input function to ask the user for the file name and determine the extension by taking the last section when split based on a period (.
Now let’s flesh out asking for the filename and loading the file. Assuming nothing goes wrong, the else section will execute once the try section is completed.
#PYTHON JSON TO CSV CONVERTER CODE#
If you’re still unsure about how the code block works, the try section will execute and if anything goes wrong the except section will take place. exiting:",e) exit() else: # convert the file and save the output Here’s the outlined structure: try: # ask for the filename # load data except Exception as e: # print error message, exit script print("Error opening file. So we’re going to use a try/except/else statement to control the flow of our script. We could do a simple input, however, if the file doesn’t exist, the rest of our script won’t work. From here, the next step is to ask for the file to load.