def print_dict(data: dict, scroll=True): text = json.dumps(data, indent=4) lex = JsonLexer() tokens = lex.get_tokens(text) out = [] for tok in tokens: if tok[0] == Token.Text: out.append(tok[1]) elif tok[0] == Token.Punctuation: out.append(tok[1]) elif tok[0] == Token.Name.Tag: out.append("<green>{}</green>".format(tok[1])) elif tok[0] == Token.Literal.Number.Integer: out.append("<orange>{}</orange>".format(tok[1])) elif tok[0] == Token.Keyword.Constant: out.append("<red>{}</red>".format(tok[1])) elif tok[0] == Token.Literal.Number.Float: out.append("<yellow>{}</yellow>".format(tok[1])) else: out.append(tok[1]) output.text += "\n{}".format("".join(out)) if scroll: output.cursor_position = len(output.text)
def main(jwt, keys, quiet): _jw = jwe.factory(jwt) if _jw: if not quiet: print("Encrypted JSON Web Token") print('Headers: {}'.format(_jw.jwt.headers)) if keys: res = _jw.decrypt(keys=keys) json_object = json.loads(res) json_str = json.dumps(json_object, indent=2) print(highlight(json_str, JsonLexer(), TerminalFormatter())) else: print("No keys can't decrypt") sys.exit(1) else: _jw = jws.factory(jwt) if _jw: if quiet: json_object = json.loads(_jw.jwt.part[1].decode("utf-8")) json_str = json.dumps(json_object, indent=2) print(highlight(json_str, JsonLexer(), TerminalFormatter())) else: print("Signed JSON Web Token") print('Headers: {}'.format(_jw.jwt.headers)) if keys: res = _jw.verify_compact(keys=keys) print('Verified message: {}'.format(res)) else: json_object = json.loads(_jw.jwt.part[1].decode("utf-8")) json_str = json.dumps(json_object, indent=2) print('Unverified message: {}'.format( highlight(json_str, JsonLexer(), TerminalFormatter())))
def print_response(txt): response_json = json.loads(txt) colorful_json = highlight(json.dumps(response_json, indent=4), JsonLexer(), TerminalFormatter()) print(colorful_json) #pprint.pprint(response_json) print('Chain length: ' + str(len(response_json)))
def pretty_print_body(fmt, body): try: bstr = body.decode() if fmt.lower() == 'json': d = json.loads(bstr.strip()) s = json.dumps(d, indent=4, sort_keys=True) print(pygments.highlight(s, JsonLexer(), TerminalFormatter())) elif fmt.lower() == 'form': qs = parse_qs(bstr, keep_blank_values=True) for k, vs in qs.items(): for v in vs: s = Colors.GREEN s += '%s: ' % unquote(k) s += Colors.ENDC if v == '': s += Colors.RED s += 'EMPTY' s += Colors.ENDC else: s += unquote(v) print(s) elif fmt.lower() == 'text': print(bstr) elif fmt.lower() == 'xml': import xml.dom.minidom xml = xml.dom.minidom.parseString(bstr) print(pygments.highlight(xml.toprettyxml(), XmlLexer(), TerminalFormatter())) else: raise CommandError('"%s" is not a valid format' % fmt) except CommandError as e: raise e except Exception as e: raise CommandError('Body could not be parsed as "{}": {}'.format(fmt, e))
def pretty_print(data, arg=None): """ :param data: :param arg: """ lexer = None if arg == 'JSON': data = json.dumps(json.loads(data), indent=2) lexer = JsonLexer() elif arg == 'XML': lexer = HtmlLexer() elif arg == 'ASCII': if not data.startswith(conf.error_marker): rows = data[1:].split("\n") rows = [r.replace('"', '').split(";") for r in rows if r] data = tabulate(rows, **conf.tabulate_opts) return click.echo_via_pager(data) else: return eprint(data) if lexer: tokens = list(pygments.lex(data, lexer=lexer)) print_formatted_text(PygmentsTokens(tokens)) else: print(data)
def json_prettify(json_data): formatter = HtmlFormatter(style='colorful') json_text = highlight(json.dumps(json_data, sort_keys=True, indent=2), JsonLexer(), formatter) style = '' return mark_safe(style + json_text)
def pretty_print_body(fmt, body): try: if fmt.lower() == 'json': d = json.loads(body.strip()) s = json.dumps(d, indent=4, sort_keys=True) print pygments.highlight(s, JsonLexer(), TerminalFormatter()) elif fmt.lower() == 'form': qs = repeatable_parse_qs(body) for k, v in qs.all_pairs(): s = Colors.GREEN s += '%s: ' % urllib.unquote(k) s += Colors.ENDC s += urllib.unquote(v) print s elif fmt.lower() == 'text': print body elif fmt.lower() == 'xml': import xml.dom.minidom xml = xml.dom.minidom.parseString(body) print pygments.highlight(xml.toprettyxml(), XmlLexer(), TerminalFormatter()) else: raise PappyException('"%s" is not a valid format' % fmt) except PappyException as e: raise e except: raise PappyException('Body could not be parsed as "%s"' % fmt)
def json(value): if not isinstance(value, str): value = json_.dumps(value, indent=2, sort_keys=True) if USE_PYGMENTS: return highlight(value, JsonLexer(), HtmlFormatter()) return value
def format(self, record): try: record.message = record.getMessage() except Exception as e: record.message = "Something exploded trying to calcualte this message: " + repr( e) try: formatted = super(JSONFormatter, self).formatMessage(record) except Exception as e: formatted = "Something exploded trying to format this message: " + repr( e) try: json = self.jsonify( record, separators=(', ' if not self.indent else ',', ': ') if __debug__ else (',', ':'), indent="\t" if self.indent else None, ) except Exception as e: formatted = "JSON calculation failed: " + repr(e) json = None if json: if self.highlight: return '\n'.join([ formatted, _highlight(json, JsonLexer(tabsize=4), Terminal256Formatter(style='monokai')).strip() ]) return '\n'.join([formatted, json]).strip() return formatted
def createLexers(self): lex = {} lex['.c'] = CFamilyLexer() lex['.h'] = CFamilyLexer() lex['.cpp'] = CppLexer() lex['.hpp'] = CppLexer() lex['.css'] = CssLexer() lex['.sass'] = SassLexer() lex['.yaml'] = YamlLexer() lex['.yml'] = YamlLexer() lex['.json'] = JsonLexer() lex['.cs'] = CSharpLexer() lex['.fs'] = FSharpLexer() lex['.e'] = EiffelLexer() lex['.erl'] = ErlangLexer() lex['.hrl'] = ErlangLexer() lex['.es'] = ErlangLexer() lex['.f03'] = FortranLexer() lex['.f90'] = FortranLexer() lex['.F03'] = FortranLexer() lex['.F90'] = FortranLexer() lex['.go'] = GoLexer() lex['.hs'] = HaskellLexer() lex['.v'] = VerilogLexer() lex['.vhdl'] = VhdlLexer() lex['.vhd'] = VhdlLexer() lex['.html'] = HtmlLexer() lex['.htm'] = HtmlLexer() lex['.xhtml'] = HtmlLexer() lex['.xml'] = XmlLexer() lex['.js'] = JavascriptLexer() lex['.tex'] = TypeScriptLexer() lex['.coffee'] = CoffeeScriptLexer() lex['.java'] = JavaLexer() lex['.scala'] = ScalaLexer() lex['.kt'] = KotlinLexer() lex['.ktm'] = KotlinLexer() lex['.kts'] = KotlinLexer() lex['.lisp'] = CommonLispLexer() lex['make'] = MakefileLexer() lex['Make'] = MakefileLexer() lex['CMake'] = CMakeLexer() lex['cmake'] = CMakeLexer() lex['.m'] = MatlabLexer() lex['.mat'] = MatlabLexer() lex['.dpr'] = DelphiLexer() lex['.perl'] = PerlLexer() lex['.php'] = PhpLexer() lex['.pr'] = PrologLexer() lex['.py'] = Python3Lexer() lex['.rb'] = RubyLexer() lex['.sh'] = BashLexer() lex['.sql'] = MySqlLexer() lex['.mysql'] = MySqlLexer() lex['.tcl'] = TclLexer() lex['.awk'] = AwkLexer() return lex
def jprint(obj, colors=True): formatted_json = json.dumps(obj, sort_keys=True, indent=4) if colors: colorful_json = highlight(formatted_json, JsonLexer(), TerminalFormatter()) print(colorful_json) else: print(formatted_json)
def pretty_typeform(self, obj): formatter = HtmlFormatter(style='colorful') data = json.dumps(obj.user_flow_action.flow.context, indent=2, ensure_ascii=False) response = highlight(data.encode('utf-8'), JsonLexer(), formatter) style = "<style>" + formatter.get_style_defs() + "</style><br>" return mark_safe(style + response)
def execution_result(obj): _results = json.dumps(obj.results, indent=2) # limit the size of the output to 3000 lines _results = '\n'.join(_results.split('\n')[:3000]) html_formatter = HtmlFormatter(style='friendly') _results = highlight(_results, JsonLexer(), html_formatter) return mark_safe( f'<style>{html_formatter.get_style_defs()}</style></br>{_results}')
def nice_ping_response(self, instance): # Convert the data to sorted, indented JSON response = json.dumps(instance.ping_response, indent=2) formatter = HtmlFormatter(style='colorful') response = highlight(response, JsonLexer(), formatter) style = "<style>" + formatter.get_style_defs() + "</style><br>" # Safe the output return mark_safe(style + response)
def __init__(self, collection_file, env_file, autosave=False, style='fruity'): self.r = Requestor(collection_file, env_file) self.autosave = autosave self.http_lexer = HttpLexer() self.json_lexer = JsonLexer() self.python_lexer = Python3Lexer() self.formatter = Terminal256Formatter(style=style)
def responseParser(response): if response.status_code != 200: print("Failed") print(response.headers) print(response.status_code) print(response) else: json_str = json.dumps(response.json(), indent=2) print(highlight(json_str, JsonLexer(), TerminalFormatter()))
def __init__(self, j, *args, **kwargs): super(FormattedJsonList, self).__init__(*args, **kwargs) self.extend(j) formatted_json = json.dumps(self, indent=4, sort_keys=True, cls=DateTimeEncoder) self.colorful_json = highlight(formatted_json.encode("UTF-8"), JsonLexer(), TerminalFormatter())
def render(self, name, value, **kwargs): formatter = HtmlFormatter(linenos='table') result = json.dumps(json.loads(value), sort_keys=True, indent=4, ensure_ascii=False) result = highlight(result, JsonLexer(), formatter) return render_to_string('admin_readonly_fields/json.html', {'value': result})
def print_data(data, fmt='json'): if fmt == 'html': lexer = HtmlLexer() else: lexer = JsonLexer() if not isinstance(data, str): data = json.dumps(data, indent=2) data = re.sub('14\d{8,11}', replace_data, data) print(highlight(data, lexer, formatter))
def print_response(txt): response_json = txt.json() #subdomains = response_json['domain_siblings'] subdomains = {'domain_siblings': response_json['domain_siblings']} # print(type(subdomains)) # print(type(response_json)) # print(type(json.dumps(subdomains, indent=4))) colorful_json = highlight(json.dumps(subdomains, indent=4), JsonLexer(), TerminalFormatter()) print(colorful_json)
def render(self, name, value, attrs=None, renderer=None): formatter = HtmlFormatter(style='colorful') formatted_json = highlight(json.dumps(json.loads(value), sort_keys=True, indent=2), JsonLexer(), formatter) context = self.get_context(name, value, attrs) context['json'] = mark_safe(formatted_json) context['style'] = mark_safe("<style>" + formatter.get_style_defs() + "</style>") template = Template(self.tpl) return template.render(Context(context))
def var_2_cool_json(data): """ :param data: :return: """ output = json.dumps(data, indent=2) return highlight(output, JsonLexer(), TerminalFormatter())
def diff_prettified(self): response = json.loads(self.difference) response = json.dumps(response, sort_keys=True, indent=1, ensure_ascii=False).replace('ó', "ó") response = response[:10000] formatter = HtmlFormatter(style='colorful', lineseparator="<br>") response = highlight(response, JsonLexer(), formatter) style = "<style>" + formatter.get_style_defs() + "</style>" return mark_safe(style + response)
def fill_json(self): from .decoder import pp_json with DisableUpdates(self.json_widg): self.json_widg.setPlainText("") if not self.data: return try: j = pp_json(self.data.decode()) except Exception: return highlighted = textedit_highlight(j, JsonLexer()) self.json_widg.setHtml(highlighted)
def pretty_json(obj: Union[str, dict, list]) -> None: """ Print JSON with indentation and colours :param obj: the object to print - can be a dict or a string """ if isinstance(obj, str): try: obj = json.loads(obj) except ValueError: raise ClientException("`obj` is not a json string") json_str = json.dumps(obj, sort_keys=True, indent=2) print(highlight(json_str, JsonLexer(), TerminalFormatter()))
def __export_api_call(self, api_call): last_exchange = app_settings.app_data_cache.get_last_exchange( api_call.id) api_test_case = app_settings.app_data_cache.get_api_test_case( api_call.id) doc = f"""# {api_call.title} # {gen_given(api_call, last_exchange)} {gen_when(api_call, last_exchange)} {gen_then(api_call, last_exchange, api_test_case)} """ return highlight(doc, JsonLexer(), HtmlFormatter())
def pprint(value): formatted_value = highlight( json.dumps( value, sort_keys=True, indent=4, separators=(',', ': ') ), JsonLexer(), TerminalFormatter(bg='dark') ) print(formatted_value)
def print_result(self, data=None): data = data or self.data if isinstance(data, dict): data = self._process_dict(data) elif isinstance(data, (list, tuple)): data = [ v.decode('utf-8') if isinstance(v, bytes) else v for v in data ] elif isinstance(data, bytes): data = data.decode('utf-8') tokens = list( pygments.lex(json.dumps(data, indent=4), lexer=JsonLexer())) print_formatted_text(PygmentsTokens(tokens))
def _echo_result(cls, state, result): if not state.is_using_cli: return # A create or update method with a file to upload will return a tuple made of # a FileUploader and None. Hence, nothing to print outside. if isinstance(result, dict) or isinstance(result, list): if isinstance(result, dict): for key in ['password', 'api_key', 'upload_key', 'key']: if key in result.keys(): result[key] = result[key][:3] + 9 * '*' json_str = json.dumps(result, indent=4, sort_keys=True, ensure_ascii=False) # .strip() avoids the empty newline click.echo(highlight(json_str, JsonLexer(), TerminalFormatter()).strip())
def handle_cli_output(self, cli_process: QProcess): output: QByteArray = cli_process.readAllStandardOutput() message = output.data().decode('utf-8').strip() if message.startswith('{') or message.startswith('['): formatter = HtmlFormatter() formatter.noclasses = True formatter.linenos = False formatter.nobackground = True message = highlight(message, JsonLexer(), formatter) self.output_area.insertHtml(message) else: self.output_area.append(message)