Cvs2Json, a Python class to convert text or CSV (Comma Separated Values) to JSON (JavaScript Object Notation) format for Django model
This is my first program. It is a class module to help you to convert text or CSV to JSON format for Django model which need three properties: “pk”, “model” and “fields”. See serialization formats from Djgno more information.
Instead of using strip()
and split()
functions as the tutorials from https://www.geeksforgeeks.org/convert-text-file-to-json-in-python/ and https://github.com/jcamier/csv-json-django/blob/master/convert_csv_to_json.py. I use Python's built-in csv library. It is more easier, convenient and powerful. It was born to to read and write tabular data in CSV format which was generated by Microsoft Excel.
I developed this program to support Thai language with utf8 encoding (UNICODE) so I hope it will support any language too.
1. Import module
2. Config some variables
- The CSV file to be converted
- The JSON output file
- App and Model name
- List of fields in your model
3. Crate object to use
see more detail in file test.py
I have more 2 files
- countries.csv, It's a source file to be converted to JSON format. You can use it for testing the program.
- countries.json, This file auto generate from class. It's my JSON output file. You can run my program to get the same output format