|
| 1 | +''' |
| 2 | +Python implementation of the Yajl C json_reformat application |
| 3 | +''' |
| 4 | + |
| 5 | +import os |
| 6 | +import sys |
| 7 | +BASEPATH = os.path.dirname(os.path.realpath(__file__)) |
| 8 | +sys.path = [BASEPATH, '%s/..' %BASEPATH] + sys.path |
| 9 | +from yajl import __version__ as yajl_version |
| 10 | +from yajl import * |
| 11 | + |
| 12 | +import optparse |
| 13 | + |
| 14 | +class ReformatContentHandler(YajlContentHandler): |
| 15 | + ''' |
| 16 | + Content handler to reformat a json file using yajl_gen |
| 17 | + ''' |
| 18 | + def __init__(self, beautify=True, indent=" "): |
| 19 | + self.out = sys.stdout |
| 20 | + self.conf = yajl_gen_config(beautify, indent) |
| 21 | + def parse_start(self): |
| 22 | + self.g = yajl.yajl_gen_alloc(byref(self.conf), None) |
| 23 | + def parse_buf(self): |
| 24 | + l = c_uint() |
| 25 | + buf = POINTER(c_ubyte)() |
| 26 | + yajl.yajl_gen_get_buf(self.g, byref(buf), byref(l)) |
| 27 | + self.out.write(string_at(buf, l.value)) |
| 28 | + yajl.yajl_gen_clear(self.g) |
| 29 | + def parse_complete(self): |
| 30 | + yajl.yajl_gen_free(self.g) |
| 31 | + def yajl_null(self, ctx): |
| 32 | + yajl.yajl_gen_null(self.g) |
| 33 | + def yajl_boolean(self, ctx, boolVal): |
| 34 | + yajl.yajl_gen_bool(self.g, boolVal) |
| 35 | + def yajl_number(self, ctx, stringNum): |
| 36 | + yajl.yajl_gen_number(self.g, c_char_p(stringNum), len(stringNum)) |
| 37 | + def yajl_string(self, ctx, stringVal): |
| 38 | + yajl.yajl_gen_string(self.g, c_char_p(stringVal), len(stringVal)) |
| 39 | + def yajl_start_map(self, ctx): |
| 40 | + yajl.yajl_gen_map_open(self.g) |
| 41 | + def yajl_map_key(self, ctx, stringVal): |
| 42 | + yajl.yajl_gen_string(self.g, c_char_p(stringVal), len(stringVal)) |
| 43 | + def yajl_end_map(self, ctx): |
| 44 | + yajl.yajl_gen_map_close(self.g) |
| 45 | + def yajl_start_array(self, ctx): |
| 46 | + yajl.yajl_gen_array_open(self.g) |
| 47 | + def yajl_end_array(self, ctx): |
| 48 | + yajl.yajl_gen_array_close(self.g) |
| 49 | + |
| 50 | + |
| 51 | +def main(): |
| 52 | + opt_parser = optparse.OptionParser( |
| 53 | + description='reformat json from stdin', |
| 54 | + version='Yajl-Py for Yajl %s' %yajl_version) |
| 55 | + opt_parser.add_option("-m", |
| 56 | + dest="beautify", action="store_false", default=True, |
| 57 | + help="minimize json rather than beautify (default)") |
| 58 | + opt_parser.add_option("-u", |
| 59 | + dest="check_utf8", action='store_false', default=True, |
| 60 | + help="allow invalid UTF8 inside strings during parsing") |
| 61 | + (options, args) = opt_parser.parse_args() |
| 62 | + yajl_parser = YajlParser( |
| 63 | + ReformatContentHandler(beautify=options.beautify), |
| 64 | + check_utf8=options.check_utf8) |
| 65 | + yajl_parser.parse() |
| 66 | + |
| 67 | +if __name__ == "__main__": |
| 68 | + main() |
0 commit comments