import os
import csv
import json
from collections import OrderedDict

print("Welcome to the JSON to CSV")
print("This script will convert a JSON file to CSV or a CSV file to JSON")

# SELECT AND OPEN A CSV OR JSON FILE
try:
    print("Which file do you want to convert?")
    filename = input("Filename: ")
    extension = filename.split(".")[-1].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 ... exiting")
        exit()
except Exception as e:
    # error loading file
    print("Error loading file ... exiting:",e)
    exit()
else:
    # CONVERT CSV TO JSON
    if extension == "csv":
        keys = data[0]
        converted = []

        for i in range(1, len(data)):
            obj = OrderedDict()
            for j in range(0,len(keys)):
                if len(data[i][j]) > 0:
                    obj[keys[j]] = data[i][j]
                else:
                    obj[keys[j]] = None
            converted.append(obj)
        
    # 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[i]:
                if j not in keys:
                    keys.append(j)
        
        # map data in each row to key index
        converted = []
        converted.append(keys)

        for i in range(0,len(data)):
            row = []
            for j in range(0,len(keys)):
                if keys[j] in data[i]:
                    row.append(data[i][keys[j]])
                else:
                    row.append(None)
            converted.append(row)

    # CREATE OUTPUT FILE
    converted_file_basename = os.path.basename(filename).split(".")[0]
    converted_file_extension = ".json" if extension == "csv" else ".csv"

    if(os.path.isfile(converted_file_basename + converted_file_extension)):
        counter = 1
        while os.path.isfile(converted_file_basename + " (" + str(counter) + ")" + converted_file_extension):
            counter += 1
        converted_file_basename = converted_file_basename + " (" + str(counter) + ")"
    
    try:
        if converted_file_extension == ".json":
            with open(converted_file_basename + converted_file_extension, 'w') as outfile:
                json.dump(converted, outfile)
        elif converted_file_extension == ".csv":
            with open(converted_file_basename + converted_file_extension, 'w') as outfile:
                writer = csv.writer(outfile)
                writer.writerows(converted)
    except:
        print("Error creating file ... exiting")
    else:
        print("File created:",converted_file_basename + converted_file_extension) 

Python Online Compiler

Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.

Taking inputs (stdin)

OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.

import sys
name = sys.stdin.readline()
print("Hello "+ name)

About Python

Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.

Tutorial & Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition IF-ELSE is used.

if conditional-expression
    #code
elif conditional-expression
    #code
else:
    #code

Note:

Indentation is very important in Python, make sure the indentation is followed correctly

2. For:

For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.

Example:

mylist=("Iphone","Pixel","Samsung")
for i in mylist:
    print(i)

3. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while condition  
    #code 

Collections

There are four types of collections in Python.

1. List:

List is a collection which is ordered and can be changed. Lists are specified in square brackets.

Example:

mylist=["iPhone","Pixel","Samsung"]
print(mylist)

2. Tuple:

Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.

Example:

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)

Below throws an error if you assign another value to tuple again.

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)

3. Set:

Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.

Example:

myset = {"iPhone","Pixel","Samsung"}
print(myset)

4. Dictionary:

Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.

Example:

mydict = {
    "brand" :"iPhone",
    "model": "iPhone 11"
}
print(mydict)

Supported Libraries

Following are the libraries supported by OneCompiler's Python compiler

NameDescription
NumPyNumPy python library helps users to work on arrays with ease
SciPySciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation
SKLearn/Scikit-learnScikit-learn or Scikit-learn is the most useful library for machine learning in Python
PandasPandas is the most efficient Python library for data manipulation and analysis
DOcplexDOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling