Python pygments.lexers.JsonLexer() Examples

The following are 30 code examples of pygments.lexers.JsonLexer(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pygments.lexers , or try the search function .
Example #1
Source File: cli.py    From jc with MIT License 8 votes vote down vote up
def json_out(data, pretty=False, mono=False, piped_out=False):

    if not mono and not piped_out:
        # set colors
        class JcStyle(Style):
            styles = set_env_colors()

        if pretty:
            print(highlight(json.dumps(data, indent=2), JsonLexer(), Terminal256Formatter(style=JcStyle))[0:-1])
        else:
            print(highlight(json.dumps(data), JsonLexer(), Terminal256Formatter(style=JcStyle))[0:-1])
    else:
        if pretty:
            print(json.dumps(data, indent=2))
        else:
            print(json.dumps(data)) 
Example #2
Source File: tcshow.py    From tcconfig with MIT License 6 votes vote down vote up
def print_tc(text, is_colorize):
    try:
        from pygments import highlight
        from pygments.lexers import JsonLexer
        from pygments.formatters import TerminalTrueColorFormatter

        pygments_installed = True
    except ImportError:
        pygments_installed = False

    if is_colorize and pygments_installed:
        print(
            highlight(
                code=text, lexer=JsonLexer(), formatter=TerminalTrueColorFormatter(style="monokai")
            )
        )
    else:
        print(text) 
Example #3
Source File: __main__.py    From pingparsing with MIT License 6 votes vote down vote up
def print_result(text: str, colorize: bool) -> None:
    if not sys.stdout.isatty() or not colorize:
        # avoid to colorized when piped or redirected
        print(text)
        return

    try:
        from pygments import highlight
        from pygments.lexers import JsonLexer
        from pygments.formatters import TerminalTrueColorFormatter

        print(
            highlight(
                code=text, lexer=JsonLexer(), formatter=TerminalTrueColorFormatter(style="monokai")
            ).strip()
        )
    except ImportError:
        print(text) 
Example #4
Source File: pygments_highlights.py    From ara with GNU General Public License v3.0 6 votes vote down vote up
def format_data(data):
    formatter = HtmlFormatter(cssclass="codehilite")

    if data is None:
        return data

    if isinstance(data, bool) or isinstance(data, int) or isinstance(data, float):
        return highlight(str(data), TextLexer(), formatter)
    elif isinstance(data, str):
        try:
            data = json.dumps(json.loads(data), indent=4, sort_keys=True)
            lexer = JsonLexer()
        except (ValueError, TypeError):
            lexer = TextLexer()
    elif isinstance(data, dict) or isinstance(data, list):
        data = json.dumps(data, indent=4, sort_keys=True)
        lexer = JsonLexer()
    else:
        lexer = TextLexer()

    lexer.stripall = True
    return highlight(data, lexer, formatter) 
Example #5
Source File: test_data.py    From pygments with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_basic_bare(lexer_bare):
    # This is the same as testBasic for JsonLexer above, except the
    # enclosing curly braces are removed.
    fragment = u'"foo": "bar", "foo2": [1, 2, 3]\n'
    tokens = [
        (Token.Name.Tag, u'"foo"'),
        (Token.Punctuation, u':'),
        (Token.Text, u' '),
        (Token.Literal.String.Double, u'"bar"'),
        (Token.Punctuation, u','),
        (Token.Text, u' '),
        (Token.Name.Tag, u'"foo2"'),
        (Token.Punctuation, u':'),
        (Token.Text, u' '),
        (Token.Punctuation, u'['),
        (Token.Literal.Number.Integer, u'1'),
        (Token.Punctuation, u','),
        (Token.Text, u' '),
        (Token.Literal.Number.Integer, u'2'),
        (Token.Punctuation, u','),
        (Token.Text, u' '),
        (Token.Literal.Number.Integer, u'3'),
        (Token.Punctuation, u']'),
        (Token.Text, u'\n'),
    ]
    assert list(lexer_bare.get_tokens(fragment)) == tokens 
Example #6
Source File: echo_error.py    From ray with Apache License 2.0 5 votes vote down vote up
def pformat_color_json(d):
    """Use pygments to pretty format and colorize dictionary"""
    formatted_json = json.dumps(d, sort_keys=True, indent=4)

    colorful_json = highlight(formatted_json, lexers.JsonLexer(),
                              formatters.TerminalFormatter())

    return colorful_json 
Example #7
Source File: echo_actor.py    From ray with Apache License 2.0 5 votes vote down vote up
def pformat_color_json(d):
    """Use pygments to pretty format and colorize dictionary"""
    formatted_json = json.dumps(d, sort_keys=True, indent=4)

    colorful_json = highlight(formatted_json, lexers.JsonLexer(),
                              formatters.TerminalFormatter())

    return colorful_json 
Example #8
Source File: echo.py    From ray with Apache License 2.0 5 votes vote down vote up
def pformat_color_json(d):
    """Use pygments to pretty format and colorize dictionary"""
    formatted_json = json.dumps(d, sort_keys=True, indent=4)

    colorful_json = highlight(formatted_json, lexers.JsonLexer(),
                              formatters.TerminalFormatter())

    return colorful_json 
Example #9
Source File: echo_actor_batch.py    From ray with Apache License 2.0 5 votes vote down vote up
def pformat_color_json(d):
    """Use pygments to pretty format and colorize dictionary"""
    formatted_json = json.dumps(d, sort_keys=True, indent=4)

    colorful_json = highlight(formatted_json, lexers.JsonLexer(),
                              formatters.TerminalFormatter())

    return colorful_json 
Example #10
Source File: echo_full.py    From ray with Apache License 2.0 5 votes vote down vote up
def pformat_color_json(d):
    """Use pygments to pretty format and colorize dictionary"""
    formatted_json = json.dumps(d, sort_keys=True, indent=4)

    colorful_json = highlight(formatted_json, lexers.JsonLexer(),
                              formatters.TerminalFormatter())

    return colorful_json


# initialize ray serve system. 
Example #11
Source File: test_data.py    From pygments with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def lexer_json():
    yield JsonLexer() 
Example #12
Source File: lncli.py    From lndmanage with MIT License 5 votes vote down vote up
def lncli(self, command):
        """
        Invokes the lncli command line interface for lnd.

        :param command: list of command line arguments
        :return:
            int: error code
        """

        cmd = self.lncli_command + command
        logger.debug('executing lncli %s', ' '.join(cmd))
        proc = subprocess.run(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )

        # check if the output can be decoded from valid json
        try:
            json.loads(proc.stdout)
            # convert json into color coded characters
            colorful_json = highlight(
                proc.stdout,
                lexers.JsonLexer(),
                formatters.TerminalFormatter()
            )
            logger.info(colorful_json)

        # usually errors and help are not json, handle them here
        except ValueError:
            logger.info(proc.stdout.decode('utf-8'))
            logger.info(proc.stderr.decode('utf-8'))

        return proc.returncode 
Example #13
Source File: main_config.py    From evo with GNU General Public License v3.0 5 votes vote down vote up
def log_info_dict_json(data_str, colored=True):
    data_str = json.dumps(data_str, indent=4, sort_keys=True)
    if colored and os.name != "nt":
        data_str = highlight(data_str, lexers.JsonLexer(),
                             formatters.Terminal256Formatter(style="monokai"))
    logger.info(data_str) 
Example #14
Source File: websocket_wrapper.py    From websocket-fuzzer with GNU General Public License v3.0 5 votes vote down vote up
def json_highlight(self, message):
        try:
            json_object = json.loads(message)
        except:
            return message
        else:
            json_str = json.dumps(json_object, indent=4, sort_keys=True)
            highlighted = highlight(json_str, JsonLexer(), TerminalFormatter())
            return highlighted + '\n\n' 
Example #15
Source File: presenter.py    From gigalixir-cli with MIT License 5 votes vote down vote up
def echo_json(data):
    formatted_json = json.dumps(data, indent=2, sort_keys=True)
    colorful_json = highlight(unicode(formatted_json), lexers.JsonLexer(), formatters.TerminalFormatter())
    click.echo(colorful_json) 
Example #16
Source File: main_config.py    From evo_slam with GNU General Public License v3.0 5 votes vote down vote up
def log_info_dict_json(data_str, colored=True):
    data_str = json.dumps(data_str, indent=4, sort_keys=True)
    if colored and os.name != "nt":
        data_str = highlight(data_str, lexers.JsonLexer(),
                             formatters.Terminal256Formatter(style="monokai"))
    logger.info(data_str) 
Example #17
Source File: __init__.py    From ansible-inventory with GNU General Public License v3.0 5 votes vote down vote up
def __print_vars( self, e_vars, pre_middle_var, pre_last_var ):
    e_line = ''
    e_vars_keys = []
    for v in e_vars:
      e_vars_keys.append( v )

    if e_vars_keys:
      e_vars_keys.sort()
      last_key = e_vars_keys[-1]
      longest_key = self.C(e_vars_keys[0]).__len__()
      for v in e_vars_keys:
        if self.C(v).__len__() > longest_key:
          longest_key = self.C(v).__len__()

      for v in e_vars_keys:
        if v == last_key:
          e_line+= pre_last_var
        else:
          e_line+= pre_middle_var

        var_line = '╴%%-%ds = %%s\n' % longest_key

        if isinstance( e_vars[v], dict ):
          if self.color.use_colors:
            from pygments import highlight, lexers, formatters
            var_dict = highlight(json.dumps(e_vars[v], sort_keys=True, indent=2),
                                      lexers.JsonLexer(),
                                      formatters.Terminal256Formatter(style='vim'))
            var_dict = var_dict.replace("\n", "\n  │       │ ")
          else:
            var_dict = json.dumps(e_vars[v], sort_keys=True, indent=2).replace("\n", "\n  │       │ ")
          e_line+= var_line % (self.C(v), var_dict)
        else:
          e_line+= var_line % (self.C(v), e_vars[v])

    return e_line 
Example #18
Source File: ui.py    From uptick with MIT License 5 votes vote down vote up
def format_dict(tx):
    from pygments import highlight, lexers, formatters

    json_raw = json.dumps(tx, sort_keys=True, indent=4)
    return highlight(
        bytes(json_raw, "UTF-8"), lexers.JsonLexer(), formatters.TerminalFormatter()
    ) 
Example #19
Source File: misc.py    From nephos with Apache License 2.0 5 votes vote down vote up
def pretty_print(string):
    """Pretty print a JSON string.

    Args:
        string (str): String we want to pretty print.
    """
    return highlight(string, JsonLexer(), TerminalFormatter()) 
Example #20
Source File: run_commands.py    From stackhut with Apache License 2.0 5 votes vote down vote up
def test_interactive(self, service_name):
            # get the contract
            contract = rpc.load_contract_file()
            interfaces = contract.interfaces
            log.info("Service has {} interface(s) - {}".format(len(interfaces), list(interfaces.keys())))

            for i in contract.interfaces.values():
                log.info("Interface '{}' has {} function(s):".
                         format(i.name, len(i.functions)))
                for f in i.functions.values():
                    log.info("\t{}".format(rpc.render_signature(f)))

            while True:
                (iface, fname) = prompt('Enter Interface.Function to test: ').split('.')
                f = contract.interface(iface).function(fname)

                values = [prompt('Enter "{}" value for {}: '.format(p.type, p.name))
                          for p in f.params]
                eval_values = [json.loads(x) for x in values]

                if utils.VERBOSE:
                    pp_values = highlight(json.dumps(eval_values, indent=4), JsonLexer(), Terminal256Formatter())
                    log.debug("Calling {} with {}".format(f.full_name, pp_values))

                msg = {
                    "service": service_name,
                    "request": {
                        "method": f.full_name,
                        "params": eval_values
                    }
                }

                self.call_service(msg) 
Example #21
Source File: run_commands.py    From stackhut with Apache License 2.0 5 votes vote down vote up
def call_service(self, msg):
        r = stackhut_api_call('run', msg)
        result = highlight(json.dumps(r, indent=4), JsonLexer(), Terminal256Formatter())
        log.info("Service {} returned - \n{}".format(utils.SERVER_URL, result)) 
Example #22
Source File: __init__.py    From cs with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _format_json(data, theme):
    """Pretty print a dict as a JSON, with colors if pygments is present."""
    output = json.dumps(data, indent=2, sort_keys=True)

    if pygments and sys.stdout.isatty():
        style = get_style_by_name(theme)
        formatter = Terminal256Formatter(style=style)
        return pygments.highlight(output, JsonLexer(), formatter)

    return output 
Example #23
Source File: common.py    From omnibus with MIT License 5 votes vote down vote up
def pp_json(data):
    if data is None:
        warning('No data returned from module.')
    else:
        print(highlight(unicode(json.dumps(data, indent=4, default=jsondate), 'UTF-8'),
            lexers.JsonLexer(), formatters.TerminalFormatter())) 
Example #24
Source File: utils.py    From grafcli with MIT License 5 votes vote down vote up
def json_pretty(data, colorize=False):
    pretty = json.dumps(data,
                        sort_keys=True,
                        indent=4,
                        separators=(',', ': '))

    if colorize:
        pretty = highlight(pretty, lexers.JsonLexer(), formatters.TerminalFormatter())

    return pretty.strip() 
Example #25
Source File: utils.py    From airflow with Apache License 2.0 5 votes vote down vote up
def get_attr_renderer():
    """Return Dictionary containing different Pygements Lexers for Rendering & Highlighting"""
    return {
        'bash_command': lambda x: render(x, lexers.BashLexer),
        'hql': lambda x: render(x, lexers.SqlLexer),
        'sql': lambda x: render(x, lexers.SqlLexer),
        'doc': lambda x: render(x, lexers.TextLexer),
        'doc_json': lambda x: render(x, lexers.JsonLexer),
        'doc_rst': lambda x: render(x, lexers.RstLexer),
        'doc_yaml': lambda x: render(x, lexers.YamlLexer),
        'doc_md': wrapped_markdown,
        'python_callable': lambda x: render(get_python_source(x), lexers.PythonLexer),
    } 
Example #26
Source File: __init__.py    From mqtt-pwn with GNU General Public License v3.0 5 votes vote down vote up
def prettify_json(some_text):
    try:
        return highlight(
            json.dumps(json.loads(some_text), indent=4),
            lexers.JsonLexer(),
            formatters.TerminalFormatter())
    except:
        return some_text 
Example #27
Source File: __init__.py    From RESTinstance with Apache License 2.0 5 votes vote down vote up
def log_json(json, header="", also_console=True, sort_keys=False):
        json = dumps(
            json,
            ensure_ascii=False,
            indent=4,
            separators=(",", ": "),
            sort_keys=sort_keys,
        )
        logger.info("{}\n{}".format(header, json))  # no coloring for log.html
        if also_console:
            json_data = highlight(
                json, lexers.JsonLexer(), formatters.TerminalFormatter()
            )
            logger.console("{}\n{}".format(header, json_data), newline=False)
        return json 
Example #28
Source File: utils.py    From PyInquirer with MIT License 5 votes vote down vote up
def print_json(data):
    #colorful_json = highlight(unicode(format_json(data), 'UTF-8'),
    #                          lexers.JsonLexer(),
    #                          formatters.TerminalFormatter())
    pprint(colorize_json(format_json(data))) 
Example #29
Source File: utils.py    From PyInquirer with MIT License 5 votes vote down vote up
def colorize_json(data):
    try:
        from pygments import highlight, lexers, formatters
        if PY3:
            if isinstance(data, bytes):
                data = data.decode('UTF-8')
        else:
            if not isinstance(data, unicode):
                data = unicode(data, 'UTF-8')
        colorful_json = highlight(data,
                                  lexers.JsonLexer(),
                                  formatters.TerminalFormatter())
        return colorful_json
    except ModuleNotFoundError:
        return data 
Example #30
Source File: views.py    From PrivacyScore with GNU General Public License v3.0 5 votes vote down vote up
def site_result_json(request: HttpRequest, site_id: int) -> HttpResponse:
    if 'at' in request.GET:
        # Check that the site even exists
        site = get_object_or_404(Site, pk=site_id)

        # TODO sanity check timestamp
        try:
            timestamp = datetime.strptime(request.GET['at'], "%Y-%m-%d")
        except:
            return render(request, 'frontend/site_result_json.html', {'site': site, 'highlighted_code': 'Incorrect timestamp format'})
        try:
            scan = Scan.objects.filter(site=site).filter(end__lte=timestamp).order_by('-end').first()
            scan_result = ScanResult.objects.get(scan=scan).result
        except Exception as e:
            scan_result = None
    else:
        site = get_object_or_404(Site.objects.annotate_most_recent_scan_result(), pk=site_id)
        scan_result = site.last_scan__result if site.last_scan__result else {}
    if 'raw' in request.GET:
        return JsonResponse(scan_result)
    code = json.dumps(scan_result, indent=2)
    if scan_result is not None:
        highlighted_code = mark_safe(highlight(code, JsonLexer(), HtmlFormatter()))
    else:
        highlighted_code = 'No scan data found for these parameters'
    return render(request, 'frontend/site_result_json.html', {
        'site': site,
        'highlighted_code': highlighted_code
    })