Created
July 22, 2020 13:21
-
-
Save akarsh1995/a914c409c5a025e9e38cbcd0646d036e to your computer and use it in GitHub Desktop.
# Script --> Convert csv file to json with this clean and elegant script. Swipe Right # ππ».
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import csv | |
| import json | |
| from io import StringIO | |
| default_csv_text = '''album,year,US_peak_chart_post | |
| The White Stripes,1999,- | |
| De Stijl,2000,- | |
| White Blood Cells,2001,61''' | |
| # convert csv to json function | |
| def csv_to_json(conn): | |
| csv_reader = csv.reader(conn, delimiter=',') | |
| # read the header and use it as keys | |
| keys = next(csv_reader) | |
| # create a list to store the rows' content | |
| row_list = [] | |
| for row in csv_reader: | |
| # pair up the keys and row content to map keys against values | |
| key_value_pairing = dict(zip(keys, row)) | |
| row_list.append(key_value_pairing) | |
| # return the resulting row_list as json | |
| return json.dumps(row_list) | |
| if __name__ == '__main__': | |
| csv_file_or_text = input('Enter the file name or paste the csv content.') | |
| if not csv_file_or_text: | |
| csv_file_or_text = default_csv_text | |
| input_is_a_file = csv_file_or_text.endswith('.csv') | |
| if input_is_a_file: | |
| connection = open(csv_file_or_text, 'r') | |
| else: | |
| connection = StringIO(csv_file_or_text) | |
| # do anything with the json you want | |
| print(csv_to_json(connection)) | |
| connection.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment