Convert CSV to JSON in Python
CSV
CSV (Comma Separated Values) is a most common file format that is widely supported by many platforms and applications. It is easier to export data as a csv dump from one system to another system. In Python it is simple to read data from csv file and export data to csv. The csv package comes with very handy methods and arguments to read and write csv file.
Example:
User,Country,Age
Alex,US,25
Ben,US,24
Dennis,UK,25
Yuvi,IN,24
JSON
JSON( Java Script Object Notation) is a lightweight text based data-interchange format which is completely language independent. It is based on JavaScript. Easy to understand, manipulate and generate. In Python there are lot of packages to simplify working with json. We are going to use json module in this tutorial.
Example:
{
"Name" : "Alex",
"City" : "Chennai",
"Country" : "India",
"Age" : 25,
"Skills" : [ "Java", "JSP"]
}
Steps to Convert CSV into JSON
Read CSV file using Python CSV DictReader
Convert the csv data into JSON or Pretty print JSON if required
Write the JSON to output file
Code
csv-json.py
#!/usr/bin/python
import sys, getopt
import csv
import json
#Get Command Line Arguments
def main(argv):
input_file = ''
output_file = ''
format = ''
try:
opts, args = getopt.getopt(argv,"hi:o:f:",["ifile=","ofile=","format="])
except getopt.GetoptError:
print 'csv_json.py -i -o -f <dump/pretty>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'csv_json.py -i -o -f <dump/pretty>'
sys.exit()
elif opt in ("-i", "--ifile"):
input_file = arg
elif opt in ("-o", "--ofile"):
output_file = arg
elif opt in ("-f", "--format"):
format = arg
read_csv(input_file, output_file, format)
#Read CSV File
def read_csv(file, json_file, format):
csv_rows = []
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
title = reader.fieldnames
for row in reader:
csv_rows.extend([{title[i]:row[title[i]] for i in range(len(title))}])
write_json(csv_rows, json_file, format)
#Convert csv data into json and write it
def write_json(data, json_file, format):
with open(json_file, "w") as f:
if format == "pretty":
f.write(json.dumps(data, sort_keys=False, indent=4, separators=(',', ': '),encoding="utf-8",ensure_ascii=False))
else:
f.write(json.dumps(data))
if __name__ == "__main__":
main(sys.argv[1:])
How to run?
Run the script via command line.
To print json dump
python csv-json.py -i users.csv -o users.json -f dump
To print json in pretty format
python csv-json.py -i users.csv -o users.json -f pretty
原文