我们从Python开源项目中,提取了以下19个代码示例,用于说明如何使用pygments.lexers.JsonLexer()。
def setup(app): # enable Pygments json lexer try: import pygments if pygments.__version__ >= '1.5': # use JSON lexer included in recent versions of Pygments from pygments.lexers import JsonLexer else: # use JSON lexer from pygments-json if installed from pygson.json_lexer import JSONLexer as JsonLexer except ImportError: pass # not fatal if we have old (or no) Pygments and no pygments-json else: app.add_lexer('json', JsonLexer()) return {"parallel_read_safe": True}
def data_prettified(instance): """Function to display pretty version of our data""" # Convert the data to sorted, indented JSON response = json.dumps(instance, sort_keys=True, indent=2) # Truncate the data. Alter as needed #response = response[:5000] # Get the Pygments formatter formatter = HtmlFormatter(style='colorful') # Highlight the data response = highlight(response, JsonLexer(), formatter) # Get the stylesheet style = "<style>" + formatter.get_style_defs() + "</style><br>" # Safe the output return mark_safe(style + response)
def jsonify(obj): """ Convert serializable object to string. If Pygments is present, it will be used to colorify the json blob. :param list[dict] obj: object to be serialized. :returns: serialized json string. :rtype: string """ formatted_json = json.dumps(stringify({"results": obj}), indent=4) try: from pygments import highlight, lexers, formatters colorful_json = highlight( formatted_json, lexers.JsonLexer(), formatters.TerminalFormatter() ) except ImportError: return formatted_json return colorful_json
def site_result_json(request: HttpRequest, site_id: int) -> HttpResponse: 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) highlighted_code = mark_safe(highlight(code, JsonLexer(), HtmlFormatter())) return render(request, 'frontend/site_result_json.html', { 'site': site, 'highlighted_code': highlighted_code })
def colorize_json(data): colorful_json = highlight(unicode(data, 'UTF-8'), lexers.JsonLexer(), formatters.TerminalFormatter()) return colorful_json
def print_json(data): #colorful_json = highlight(unicode(format_json(data), 'UTF-8'), # lexers.JsonLexer(), # formatters.TerminalFormatter()) print(colorize_json(format_json(data)))
def handle(self, *args, **options): try: from pygments import lexers except ImportError: self.stdout.write("This command requires Pygments package.") self.stdout.write("Please install it with:\n\n") self.stdout.write(" pip install Pygments\n\n") return # Invocation examples _process("bash", lexers.BashLexer()) _process("browser", lexers.JavascriptLexer()) _process("crontab", lexers.BashLexer()) _process("python", lexers.PythonLexer()) _process("php", lexers.PhpLexer()) _process("powershell", lexers.shell.PowerShellLexer()) _process("node", lexers.JavascriptLexer()) # API examples _process("list_checks_request", lexers.BashLexer()) _process("list_checks_response", lexers.JsonLexer()) _process("create_check_request", lexers.BashLexer()) _process("create_check_response", lexers.JsonLexer()) _process("pause_check_request", lexers.BashLexer()) _process("pause_check_response", lexers.JsonLexer())
def setup(app): # enable Pygments json lexer try: import pygments if pygments.__version__ >= '1.5': # use JSON lexer included in recent versions of Pygments from pygments.lexers import JsonLexer else: # use JSON lexer from pygments-json if installed from pygson.json_lexer import JSONLexer as JsonLexer except ImportError: pass # not fatal if we have old (or no) Pygments and no pygments-json else: app.add_lexer('json', JsonLexer())
def json(formatted_json): return pygments.highlight(formatted_json, lexers.JsonLexer(), formatters.TerminalFormatter())
def pretty_json_as_html(data, sort_keys=True): response = json.dumps(data, sort_keys=sort_keys, indent=2) # Truncate the data. Alter as needed response = response[:5000] # Get the Pygments formatter formatter = HtmlFormatter(style='colorful') # Highlight the data response = highlight(response, JsonLexer(), formatter) # Get the stylesheet style = "<style>" + formatter.get_style_defs() + "</style><br>" # Safe the output return mark_safe(style + response)
def output_format(obj): ''' python2/3 ??????? obj is dict http://stackoverflow.com/questions/35950573/python-unicode-string-to-javascript ''' formatted_json = json.dumps(obj, sort_keys=True, indent=4,ensure_ascii=False).encode('utf8') if (sys.version_info > (3, 0)): # Python 3 code in this block colorful_json = highlight(formatted_json, lexers.JsonLexer(), formatters.TerminalFormatter()) return colorful_json else: colorful_json = highlight(unicode(formatted_json, 'UTF-8'), lexers.JsonLexer(), formatters.TerminalFormatter()) return colorful_json #??????
def _highlight_json(json_value): """ :param json_value: JSON value to syntax-highlight :type json_value: dict, list, number, string, boolean, or None :returns: A string representation of the supplied JSON value, highlighted for a terminal that supports ANSI colors. :rtype: str """ return pygments.highlight( json_value, JsonLexer(), Terminal256Formatter()).strip()
def format_json_color(obj): from pygments import highlight, lexers, formatters return highlight(format_json(obj), lexers.JsonLexer(), formatters.TerminalFormatter()) # pylint: disable=no-member
def highlight_json(d, style=STYLE): """JSON Syntax highlighter.""" try: formatter = TerminalFormatter(colorscheme=get_style(style)) except (NameError, AttributeError): return d return pygments.highlight(d, JsonLexer(), formatter)
def get_prettyjson_html(api_key): boite = get_object_or_404(Boite, api_key=api_key) # Example from https://www.pydanny.com/pretty-formatting-json-django-admin.html response = json.dumps(boite.get_apps_dictionary(), sort_keys=True, indent=2) response = response[:5000] formatter = HtmlFormatter(style='friendly') response = highlight(response, JsonLexer(), formatter) style = "<style>" + formatter.get_style_defs() + "</style><br>" return mark_safe(style + response)
def printbody(step,*,file, id,http_part, colourful): if http_part == 'response': try: printoutput = json.dumps(step.response.body,indent=4, sort_keys=True) isJsonPayload = True except JSONDecodeError as e: # if it doesn't parse as JSON, set it as raw output printoutput = step.response.body colourful = False # and if it is not JSON, turn off colourful output. isJsonPayload = False else: ## http_part == request: try: printoutput = json.dumps(step.request.body,indent=4, sort_keys=True) isJsonPayload = True except JSONDecodeError as e: # if it doesn't parse as JSON, set it as raw output printoutput = step.request.body colourful = False # and if it is not JSON, turn off colourful output. isJsonPayload = False if colourful and isJsonPayload: print(highlight(printoutput,lexers.JsonLexer(),formatters.TerminalFormatter()),file=file) else: #not JSON payload, and therefore, not colourful either print(printoutput,file=file) # define regex patterns.
def writeOutput(self, *, writeformat, writefile, req): """Writes the output to the writefile in the format specified""" vlog("Generating output of step: " + str(self.id) +" " + self.step.name + ". Format=" + writeformat) if writeformat == 'json': formatted_json = json.dumps(self.step.response.body,indent=4, sort_keys=True) #colorise the json if sys.stdout.isatty(): from pygments import highlight, lexers, formatters colorful_json = highlight(formatted_json, lexers.JsonLexer(), formatters.TerminalFormatter()) print(colorful_json, file=writefile) else: print(formatted_json, file=writefile) else: # format is raw-(all|response) printstepcolophon(self.step,id=self.id, file=writefile) if bprc.cli.args.nocolor: colourful = False else: colourful = sys.stdout.isatty() if writeformat == 'raw-all': ## need to write the http resquest first. print("-- Request --", file=writefile) printhttprequest(self.step, id=self.id, file=writefile, colourful=colourful) printheaders(self.step, id=self.id,file=writefile, http_part='request', colourful=colourful) logging.debug("PRINTING REQUEST HEADERS") if self.step.request.body: logging.debug("Req.body==" +req.body) try: # if this doesn't decode then it's probably not JSON, just print it # without a decode self.step.request.body=json.loads(req.body) except JSONDecodeError as e: self.step.request.body=req.body printbody(self.step, id=self.id, file=writefile, http_part='request', colourful=colourful) print("-- Response --", file=writefile) # now write the response printhttpresponse(self.step, id=self.id, file=writefile, colourful=colourful) printheaders(self.step, id=self.id, file=writefile, http_part='response', colourful=colourful) if self.step.response.body: printbody(self.step, id=self.id, file=writefile, http_part='response', colourful=colourful)