Skip to content

Commit f52fe2b

Browse files
committed
Add JSON as a supported output format
Signed-off-by: Philippe Ombredanne <pombredanne@nexb.com>
1 parent a3d058f commit f52fe2b

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

pkginfo/commandline.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,9 @@
2020
from configparser import ConfigParser
2121
except ImportError: # pragma: NO COVER
2222
from ConfigParser import ConfigParser
23+
from collections import OrderedDict
2324
from csv import writer
25+
import json
2426
import optparse
2527
import os
2628
import sys
@@ -82,6 +84,11 @@ def _parse_options(args=None):
8284
help="Output as INI",
8385
)
8486

87+
parser.add_option("--json", dest="output", action="store_const",
88+
const='json',
89+
help="Output as JSON",
90+
)
91+
8592
options, args = parser.parse_args(args)
8693

8794
if len(args)==0:
@@ -174,11 +181,30 @@ def __call__(self, meta):
174181
def finish(self):
175182
self._parser.write(sys.stdout) # pragma: NO COVER
176183

184+
class JSON(Base):
185+
_fields = None
186+
def __init__(self, options):
187+
super(JSON, self).__init__(options)
188+
self._mapping = OrderedDict()
189+
190+
def __call__(self, meta):
191+
if self._fields is None:
192+
self._fields = list(meta)
193+
for field in self._fields:
194+
value = getattr(meta, field)
195+
if value and not isinstance(value, (tuple, list)):
196+
value = str(value)
197+
self._mapping[field] = value
198+
199+
def finish(self):
200+
json.dump(self._mapping, sys.stdout, indent=2, encoding='utf-8')
201+
177202
_FORMATTERS = {
178203
'simple': Simple,
179204
'single': SingleLine,
180205
'csv': CSV,
181206
'ini': INI,
207+
'json': JSON,
182208
}
183209

184210
def main(args=None):

0 commit comments

Comments
 (0)