JSON

Convert CSV to JSON in Python

字号+ 作者:H5之家 来源:H5之家 2017-07-28 18:06 我要评论( )

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

Convert CSV to JSON in Python

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

Get paths to both input csv file, output json file and json formatting via Command line arguments

 

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

Packages Used

原文

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • “Newtonsoft.Json ......”在这两个“混合\ Newtonsoft.Json.dl

    “Newtonsoft.Json ......”在这两个“混合\ Newtonsoft.Json.dl

    2017-07-29 13:03

  • json在线解码器

    json在线解码器

    2017-07-28 18:06

  • c#代码中, 如何获取网页中的json数据?

    c#代码中, 如何获取网页中的json数据?

    2017-07-28 17:06

  • JSON必知必会学习总结(一)

    JSON必知必会学习总结(一)

    2017-07-27 16:00

网友点评