Commit 7bb3f5d0 authored by hydrargyrum's avatar hydrargyrum

csv2json: transform CSV into JSON

parent a704e71e
#!/usr/bin/env python3
from argparse import ArgumentParser
from collections import OrderedDict
import csv
import json
import sys
def sniff(fn):
with open(fn) as fd:
sn = csv.Sniffer()
return sn.sniff(fd.read(1024))
def read_rows(fd, args):
if args.header:
for row in csv.DictReader(fd, delimiter=args.delimiter):
yield row
else:
for row in csv.reader(fd, delimiter=args.delimiter):
yield OrderedDict((str(n), v) for n, v in enumerate(row))
def main():
parser = ArgumentParser()
parser.add_argument('--header', action='store_true')
parser.add_argument('-d', '--delimiter', default=',')
parser.add_argument('--sniff', action='store_true')
parser.add_argument('file')
args = parser.parse_args()
with open(args.file) as fd:
data = list(read_rows(fd, args))
print(json.dumps(data))
if __name__ == '__main__':
main()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment