-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.py
69 lines (46 loc) · 1.35 KB
/
convert.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import sys
import argparse
import json
import dicttoxml
supportedFormats = ['json', 'xml']
class XMLCreator:
f = None
def __init__(self, f):
self.f = f
self.f.write('<?xml version="1.0" encoding="UTF-8" ?><root>')
def append(self, dict):
#str = dicttoxml.dicttoxml(dict)
#str = str[45:-7]
str = ''.join(["<%s>%s</%s>" % (k, v, k) for k,v in dict.items()]) #not great, but very fast
self.f.write('<item>' + str.encode('utf8') + '</item>')
def finish(self):
self.f.write('</root>')
class JSONCreator:
f = None
first = True
def __init__(self, f):
self.f = f
self.f.write('[')
def append(self, dict):
str = json.dumps(dict)
if not self.first:
self.f.write(', ')
self.f.write(str.encode('utf8'))
self.first = False
def finish(self):
self.f.write(']')
parser = argparse.ArgumentParser(description='Convert JSON-lines to other formats')
parser.add_argument('--input', '-i', dest='filename', required=True, help='input file')
parser.add_argument('--to', '-t', choices=supportedFormats, required=True, help='output format')
args = parser.parse_args()
foutput = sys.stdout
if args.to == 'xml':
creator = XMLCreator(foutput)
elif args.to == 'json':
creator = JSONCreator(foutput)
with open(args.filename) as f:
for line in f:
jsonLine = line.rstrip()
dict = json.loads(jsonLine)
creator.append(dict)
creator.finish()