Recently i have to do some json editing and here were the most used methods that might be useful for me or others someday. …..  …

Josn & CSV


import json
# CSV file to Json File
def csv_to_json(csvFilePath, jsonFilePath) -> None:
    jsonArray = []

    # Read csv file
    with open(csvFilePath, encoding='utf-8') as csvf:
        # Load csv file data using csv library's dictionary reader
        csvReader = csv.DictReader(csvf, delimiter=';')

        # Convert each csv row into python dict
        for row in csvReader:
            # add this python dict to json array
            jsonArray.append(row)

    # Convert python jsonArray to JSON String and write to file
    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
        jsonString = json.dumps(jsonArray, indent=4)
        jsonf.write(jsonString)

# Save anything to json file
def saveJsonToFile(json, filepath) -> None:
    with open(filepath, "w") as d:
        d.writelines(json)

# Load from json file to dictionary
def loadJsonFromFile(filepath) -> dict:
    with open(filepath, "r") as j:
        data = json.load(j)
    return data

if __name__ == "__main__":
    normal_list = [110, 12.3, True, False, None, "string", {"dict":123,"inception":{"deep":1,"deep":2}}]
    print(f"{'Normal:': <8}" + str(normal_list))
    print(f"{'Json:': <8}" + json.dumps(normal_list))

    saveJsonToFile(json.dumps(normal_list), "data.json")
    
    newOne = loadJsonFromFile("data.json")
    print(newOne)