diff --git a/DIRECTORY.md b/DIRECTORY.md index 66d5f8040951..b7c003a73f68 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -107,6 +107,7 @@ ## Conversions * [Binary To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_decimal.py) * [Binary To Octal](https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_octal.py) + * [Csv Json](https://github.com/TheAlgorithms/Python/blob/master/conversions/csv_json.py) * [Decimal To Any](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_any.py) * [Decimal To Binary](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_binary.py) * [Decimal To Binary Recursion](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_binary_recursion.py) diff --git a/conversions/csv_json.py b/conversions/csv_json.py new file mode 100644 index 000000000000..6fbff52bdf57 --- /dev/null +++ b/conversions/csv_json.py @@ -0,0 +1,52 @@ +""" +Functions useful for converting data from CSV to JSON and vice-versa: +* csv_to_json +* json_to_csv + +REFERENCES: +https://en.wikipedia.org/wiki/Comma-separated_values +https://en.wikipedia.org/wiki/JSON +""" + +import csv +import json +from pathlib import Path + +import pandas as pd + + +def csv_to_json(filename: str) -> str: + """ + Convert data from CSV to JSON + + >>> csv_to_json() + + >>> csv_to_json() + + """ + file = open(filename, "r") + dict_reader = csv.DictReader(file) + + dict_from_csv = list(dict_reader)[0] + json_from_csv = json.dumps(dict_from_csv) + file.close() + + return json_from_csv + + +def json_to_csv(filename: str) -> str: + """ + Convert data from JSON to CSV + + >>> json_to_csv() + + >>> json_to_csv() + + """ + jsonpath = Path(filename) + + with jsonpath.open("r", encoding="utf-8") as datafile: + data = json.loads(datafile.read()) + + df = pd.json_normalize(data) + return df