Exemplo n.º 1
0
def main():
    indent = int(os.environ.get('INDENT') or '2')
    if len(sys.argv) >= 2:
        with open(sys.argv[1]) as fo:
            data_in = fo.read()
    else:
        data_in = sys.stdin.read()

    try:
        outbuf = sys.stdout.buffer
    except AttributeError:
        outbuf = sys.stdout

    def bailout(msg):
        sys.stderr.write(
            "ERROR: fjson.py: %s; original data as follows (on stdout)\n" % (msg,))
        outbuf.write(data_in)
        return 13

    try:
        data = json.loads(data_in)
    except Exception as exc:
        return bailout("Error parsing as json: %s" % (exc,))

    try:
        data_out = json.dumps(
            data, indent=indent, sort_keys=True, ensure_ascii=False)
    except Exception as exc:
        return bailout("Error dumping as json: %s" % (exc,))

    outbuf.write(to_bytes(data_out))
    outbuf.write(b"\n")
    outbuf.flush()
Exemplo n.º 2
0
def main():

    parser = cmd_make_parser()
    params = parser.parse_args()

    # TODO?: support input file
    data_in = sys.stdin.read()

    def bailout(msg):
        sys.stderr.write(
            "ERROR: fjson_yaml: %s; original data as follows (on stdout)\n" % (msg,))
        sys.stdout.write(data_in)
        return 13

    try:
        data_data = json.loads(data_in)
    except Exception as exc:
        return bailout("Error parsing as json: %s" % (exc,))

    kwa = dict(
        default_flow_style=params.default_flow_style,
        allow_unicode=params.allow_unicode,
    )
    try:
        kwa['width'] = int(os.environ['WIDTH'])
    except Exception:
        pass

    try:
        out = yaml.safe_dump(data_data, **kwa)
    except Exception as exc:
        return bailout("Error dumping as yaml: %s" % (exc,))

    # Result:
    #   `--color=no` always skips this
    #   `--color`, `--color=yes`, `-c` always do this
    #   ``, `--color=auto` make this isatty-conditional.
    if ((params.color == 'auto' and sys.stdout.isatty()) or
            # NOTE: `'auto'` is default, `None` means it was
            # specified without an argument (equals to 'always')
            params.color in ('yes', 'always', True, None)):

        # pygments doesn't like utf-8 as-is; make it unicode
        if isinstance(out, bytes):
            out = out.decode('utf-8')

        # TODO?: support --color=auto
        out = colorize(out)

    # TODO?: support output file
    sys.stdout.write(to_bytes(out))
    if out[-1] != '\n':  # Just in case
        sys.stdout.write('\n')
    sys.stdout.flush()
Exemplo n.º 3
0
def main():
    import msgpack
    indent = int(os.environ.get('INDENT') or '2')
    data_in = sys.stdin.read()
    try:
        data = msgpack.loads(data_in)
    except Exception as exc:
        sys.stderr.write("#  -!!---- %s\n" % (exc,))
        sys.stdout.write(repr(data_in))
        return 13

    data_out = json.dumps(data, indent=indent, sort_keys=True, ensure_ascii=False)
    sys.stdout.write(to_bytes(data_out))
    sys.stdout.write("\n")
Exemplo n.º 4
0
def main():

    parser = cmd_make_parser()
    params = parser.parse_args()

    # TODO?: support input file
    data_in = sys.stdin.read()

    def bailout(msg):
        sys.stderr.write(
            "ERROR: fjson_yaml: %s; original data as follows (on stdout)\n" % (msg,))
        sys.stdout.write(data_in)
        return 13

    Loader = getattr(yaml, 'CSafeLoader', None) or yaml.SafeLoader
    try:
        data_data = yaml.load(data_in, Loader=Loader)
    except Exception as exc:
        return bailout("Error parsing as yaml: %s" % (exc,))

    kwa = dict(
        ensure_ascii=params.ensure_ascii,
    )
    if params.indent is None:
        kwa['indent'] = None if params.compact else 2
    elif params.indent == '-':
        kwa['indent'] = None
    else:
        kwa['indent'] = int(params.indent)
    kwa['separators'] = (',', ':') if params.compact else None

    try:
        out = json.dumps(data_data, **kwa)
    except Exception as exc:
        return bailout("Error dumping as json: %s" % (exc,))

    # TODO?: support output file
    sys.stdout.write(to_bytes(out))
    if out[-1] != '\n':  # Just in case
        sys.stdout.write('\n')
    sys.stdout.flush()
Exemplo n.º 5
0
 def serialize_data_ujson(self, data, context=None):  # pylint: disable=unused-argument
     import ujson
     # pylint: disable=c-extension-no-member
     data = to_bytes(ujson.dumps(data, ensure_ascii=False))
     return self.json_content_type, data
Exemplo n.º 6
0
 def serialize_data_json(self, data, context=None):  # pylint: disable=unused-argument
     """ Overridable point for json-serialization customization. """
     from .anyjson import json_dumps
     data = to_bytes(json_dumps(data))
     return self.json_content_type, data