|
20 | 20 | from configparser import ConfigParser |
21 | 21 | except ImportError: # pragma: NO COVER |
22 | 22 | from ConfigParser import ConfigParser |
| 23 | +from collections import OrderedDict |
23 | 24 | from csv import writer |
| 25 | +import json |
24 | 26 | import optparse |
25 | 27 | import os |
26 | 28 | import sys |
@@ -82,6 +84,11 @@ def _parse_options(args=None): |
82 | 84 | help="Output as INI", |
83 | 85 | ) |
84 | 86 |
|
| 87 | + parser.add_option("--json", dest="output", action="store_const", |
| 88 | + const='json', |
| 89 | + help="Output as JSON", |
| 90 | + ) |
| 91 | + |
85 | 92 | options, args = parser.parse_args(args) |
86 | 93 |
|
87 | 94 | if len(args)==0: |
@@ -174,11 +181,30 @@ def __call__(self, meta): |
174 | 181 | def finish(self): |
175 | 182 | self._parser.write(sys.stdout) # pragma: NO COVER |
176 | 183 |
|
| 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 | + |
177 | 202 | _FORMATTERS = { |
178 | 203 | 'simple': Simple, |
179 | 204 | 'single': SingleLine, |
180 | 205 | 'csv': CSV, |
181 | 206 | 'ini': INI, |
| 207 | + 'json': JSON, |
182 | 208 | } |
183 | 209 |
|
184 | 210 | def main(args=None): |
|
0 commit comments