query
stringlengths 9
60
| language
stringclasses 1
value | code
stringlengths 105
25.7k
| url
stringlengths 91
217
|
---|---|---|---|
pretty print json
|
python
|
def _json_pretty_print(self, content):
"""
Pretty print a JSON object
``content`` JSON object to pretty print
"""
temp = json.loads(content)
return json.dumps(
temp,
sort_keys=True,
indent=4,
separators=(
',',
': '))
|
https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L1215-L1228
|
pretty print json
|
python
|
def json_pretty_print(s):
'''pretty print JSON'''
s = json.loads(s)
return json.dumps(s,
sort_keys=True,
indent=4,
separators=(',', ': '))
|
https://github.com/mosesschwartz/scrypture/blob/d51eb0c9835a5122a655078268185ce8ab9ec86a/scrypture/demo_scripts/Utils/json_pretty_print.py#L8-L14
|
pretty print json
|
python
|
def pretty_json(obj):
"""
Print JSON with indentation and colours
:param obj: the object to print - can be a dict or a string
"""
if isinstance(obj, string_types):
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()))
|
https://github.com/davidhuser/dhis2.py/blob/78cbf1985506db21acdfa0f2e624bc397e455c82/dhis2/utils.py#L142-L153
|
pretty print json
|
python
|
def pretty_print (obj, indent=False):
"""
pretty print a JSON object
"""
if indent:
return json.dumps(obj, sort_keys=True, indent=2, separators=(',', ': '))
else:
return json.dumps(obj, sort_keys=True)
|
https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L792-L800
|
pretty print json
|
python
|
def pretty_print_json(self, json_string):
"""
Return formatted JSON string _json_string_.\n
Using method json.dumps with settings: _indent=2, ensure_ascii=False_.
*Args:*\n
_json_string_ - JSON string.
*Returns:*\n
Formatted JSON string.
*Example:*\n
| *Settings* | *Value* |
| Library | JsonValidator |
| Library | OperatingSystem |
| *Test Cases* | *Action* | *Argument* | *Argument* |
| Check element | ${pretty_json}= | Pretty print json | {a:1,foo:[{b:2,c:3},{d:"baz",e:4}]} |
| | Log | ${pretty_json} |
=>\n
| {
| "a": 1,
| "foo": [
| {
| "c": 3,
| "b": 2
| },
| {
| "e": 4,
| "d": "baz"
| }
| ]
| }
"""
return json.dumps(self.string_to_json(json_string), indent=2, ensure_ascii=False)
|
https://github.com/peterservice-rnd/robotframework-jsonvalidator/blob/acde5045c04d0a7b9079f22707c3e71a5d3fa724/src/JsonValidator.py#L414-L447
|
pretty print json
|
python
|
def pprint(j, no_pretty):
"""
Prints as formatted JSON
"""
if not no_pretty:
click.echo(
json.dumps(j, cls=PotionJSONEncoder, sort_keys=True, indent=4, separators=(",", ": "))
)
else:
click.echo(j)
|
https://github.com/onecodex/onecodex/blob/326a0a1af140e3a57ccf31c3c9c5e17a5775c13d/onecodex/utils.py#L112-L121
|
pretty print json
|
python
|
def pretty_print(self, obj=None):
""" Formats and prints @obj or :prop:obj
@obj: the object you'd like to prettify
"""
print(self.pretty(obj if obj is not None else self.obj))
|
https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/debug/__init__.py#L1266-L1271
|
pretty print json
|
python
|
def pretty_json(obj):
"""
Представить объект в вище json красиво отформатированной строки
:param obj:
:return:
"""
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False)
|
https://github.com/devision-io/metasdk/blob/1a1af5ceeb8ade843fd656c9c27c8b9ff789fc68/metasdk/utils.py#L41-L47
|
pretty print json
|
python
|
def print_pretty(text, **kwargs):
'''
Prints using pycolorterm formatting
:param text: Text with formatting
:type text: string
:param kwargs: Keyword args that will be passed to the print function
:type kwargs: dict
Example::
print_pretty('Hello {BG_RED}WORLD{END}')
'''
text = _prepare(text)
print('{}{}'.format(text.format(**styles).replace(styles['END'], styles['ALL_OFF']), styles['ALL_OFF']))
|
https://github.com/dnmellen/pycolorterm/blob/f650eb8dbdce1a283e7b1403be1071b57c4849c6/pycolorterm/pycolorterm.py#L71-L86
|
pretty print json
|
python
|
def prettyprint(self):
"""Return hypercat formatted prettily"""
return json.dumps(self.asJSON(), sort_keys=True, indent=4, separators=(',', ': '))
|
https://github.com/thingful/hypercat-py/blob/db24ef66ec92d74fbea90afbeadc3a268f18f6e3/hypercat/hypercat.py#L90-L92
|
pretty print json
|
python
|
def pretty_json(data):
"""Return a pretty formatted json
"""
data = json.loads(data.decode('utf-8'))
return json.dumps(data, indent=4, sort_keys=True)
|
https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/utils.py#L5-L9
|
pretty print json
|
python
|
def _dict_to_json_pretty(d, sort_keys=True):
'''
helper function to generate pretty printed json output
'''
return salt.utils.json.dumps(d, indent=4, separators=(',', ': '), sort_keys=sort_keys)
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L463-L467
|
pretty print json
|
python
|
def to_json(self, content, pretty_print=False):
""" Convert a string to a JSON object
``content`` String content to convert into JSON
``pretty_print`` If defined, will output JSON is pretty print format
"""
if PY3:
if isinstance(content, bytes):
content = content.decode(encoding='utf-8')
if pretty_print:
json_ = self._json_pretty_print(content)
else:
json_ = json.loads(content)
logger.info('To JSON using : content=%s ' % (content))
logger.info('To JSON using : pretty_print=%s ' % (pretty_print))
return json_
|
https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L460-L477
|
pretty print json
|
python
|
def pretty_print(self, obj):
"""
:param object obj:
:rtype: str
"""
s = repr(obj)
limit = output_limit()
if len(s) > limit:
if self.dom_term:
s = self.color.py_syntax_highlight(s)
s = self.dom_term.fold_text_string("", s)
else:
s = s[:limit - 3] # cut before syntax highlighting, to avoid missing color endings
s = self.color.py_syntax_highlight(s)
s += "..."
else:
s = self.color.py_syntax_highlight(s)
extra_info = self._pp_extra_info(obj)
if extra_info != "":
s += ", " + self.color.py_syntax_highlight(extra_info)
return s
|
https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L933-L953
|
pretty print json
|
python
|
def maybe_print_as_json(opts, data, page_info=None):
"""Maybe print data as JSON."""
if opts.output not in ("json", "pretty_json"):
return False
root = {"data": data}
if page_info is not None and page_info.is_valid:
meta = root["meta"] = {}
meta["pagination"] = page_info.as_dict(num_results=len(data))
if opts.output == "pretty_json":
dump = json.dumps(root, indent=4, sort_keys=True)
else:
dump = json.dumps(root, sort_keys=True)
click.echo(dump)
return True
|
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/utils.py#L107-L124
|
pretty print json
|
python
|
def json(cls, message):
""" Print a nice JSON output
Args:
message: the message to print
"""
if type(message) is OrderedDict:
pprint(dict(message))
else:
pprint(message)
|
https://github.com/nuagenetworks/monolithe/blob/626011af3ff43f73b7bd8aa5e1f93fb5f1f0e181/monolithe/lib/printer.py#L109-L119
|
pretty print json
|
python
|
def pprint(data):
"""
Returns an indented HTML pretty-print version of JSON.
Take the event_payload JSON, indent it, order the keys and then
present it as a <code> block. That's about as good as we can get
until someone builds a custom syntax function.
"""
pretty = json.dumps(data, sort_keys=True, indent=4, separators=(",", ": "))
html = pretty.replace(" ", " ").replace("\n", "<br>")
return mark_safe("<code>%s</code>" % html)
|
https://github.com/yunojuno/elasticsearch-django/blob/e8d98d32bcd77f1bedb8f1a22b6523ca44ffd489/elasticsearch_django/admin.py#L13-L24
|
pretty print json
|
python
|
def pretty_print(node):
"""漂亮地打印一个节点
Args:
node (TYPE): Description
"""
for pre, _, node in RenderTree(node):
print('{}{}'.format(pre, node.name))
|
https://github.com/mikusjelly/apkutils/blob/2db1ed0cdb610dfc55bfd77266e9a91e4764bba4/apkutils/__init__.py#L113-L120
|
pretty print json
|
python
|
def to_pretty_json(self, ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to pretty json string
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Json string
Usage:
>>> from owlmixin.samples import Human
>>> human = Human.from_dict({
... "id": 1,
... "name": "Tom",
... "favorites": [
... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... })
>>> print(human.to_pretty_json())
{
"favorites": [
{
"name": "Apple",
"names_by_lang": {
"de": "Apfel",
"en": "Apple"
}
},
{
"name": "Orange"
}
],
"id": 1,
"name": "Tom"
}
"""
return self.to_json(4, ignore_none, ignore_empty)
|
https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/transformers.py#L230-L266
|
pretty print json
|
python
|
def json_pretty_dump(obj, filename):
"""
Serialize obj as a JSON formatted stream to the given filename (
pretty printing version)
"""
with open(filename, "wt") as fh:
json.dump(obj, fh, indent=4, sort_keys=4)
|
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/util/serialization.py#L43-L49
|
pretty print json
|
python
|
def pprint(value):
"""Prints as formatted JSON"""
click.echo(
json.dumps(value,
sort_keys=True,
indent=4,
separators=(',', ': ')))
|
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/utils/formatting.py#L51-L57
|
pretty print json
|
python
|
def prettyjson(json, indentation=' '):
"""Formats a Python-object into a string in a JSON like way, but
uses triple quotes for multiline strings.
PARAMETERS:
json -- Python object that is serializable into json.
indentation -- str; represents one level of indentation
NOTES:
All multiline strings are treated as raw strings.
RETURNS:
str; the formatted json-like string.
"""
if isinstance(json, int) or isinstance(json, float):
return str(json)
elif isinstance(json, str):
if '\n' in json:
return 'r"""\n' + dedent(json) + '\n"""'
return repr(json)
elif isinstance(json, list):
lst = [indent(prettyjson(el, indentation), indentation) for el in json]
return '[\n' + ',\n'.join(lst) + '\n]'
elif isinstance(json, dict):
pairs = []
for k, v in sorted(json.items()):
k = prettyjson(k, indentation)
v = prettyjson(v, indentation)
pairs.append(indent(k + ': ' + v, indentation))
return '{\n' + ',\n'.join(pairs) + '\n}'
else:
raise exceptions.SerializeException('Invalid json type: {}'.format(json))
|
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/utils/format.py#L129-L160
|
pretty print json
|
python
|
def write_json(json_obj, filename, mode="w", print_pretty=True):
'''write_json will (optionally,pretty print) a json object to file
:param json_obj: the dict to print to json
:param filename: the output file to write to
:param pretty_print: if True, will use nicer formatting
'''
with open(filename, mode) as filey:
if print_pretty:
filey.writelines(
json.dumps(
json_obj,
indent=4,
separators=(
',',
': ')))
else:
filey.writelines(json.dumps(json_obj))
return filename
|
https://github.com/singularityhub/singularity-cli/blob/cb36b4504812ca87e29c6a40b222a545d1865799/spython/utils/fileio.py#L57-L74
|
pretty print json
|
python
|
def write_json(json_obj, filename, mode="w", print_pretty=True):
'''write_json will (optionally,pretty print) a json object to file
Parameters
==========
json_obj: the dict to print to json
filename: the output file to write to
pretty_print: if True, will use nicer formatting
'''
with open(filename, mode) as filey:
if print_pretty:
filey.writelines(print_json(json_obj))
else:
filey.writelines(json.dumps(json_obj))
return filename
|
https://github.com/singularityhub/sregistry-cli/blob/abc96140a1d15b5e96d83432e1e0e1f4f8f36331/sregistry/utils/fileio.py#L283-L297
|
pretty print json
|
python
|
def pprint(data, indent=0, end='\n'):
"""Pretty print JSON data.
Parameters
----------
data
JSON data.
indent : `int`, optional
Indent level in characters (default: 0).
end : `str`, optional
String to print after the data (default: '\\\\n').
"""
if isinstance(data, dict):
print('{')
new_indent = indent + 4
space = ' ' * new_indent
keys = list(sorted(data.keys()))
for i, k in enumerate(keys):
print(space, json.dumps(k), ': ', sep='', end='')
pprint(data[k], new_indent,
end=',\n' if i < len(keys) - 1 else '\n')
print(' ' * indent, '}', sep='', end=end)
elif isinstance(data, list):
if any(isinstance(x, (dict, list)) for x in data):
print('[')
new_indent = indent + 4
space = ' ' * new_indent
for i, x in enumerate(data):
print(space, end='')
pprint(x, new_indent,
end=',\n' if i < len(data) - 1 else '\n')
print(' ' * indent, ']', sep='', end=end)
else:
print(json.dumps(data), end=end)
else:
print(json.dumps(data), end=end)
|
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/cli/util.py#L81-L116
|
pretty print json
|
python
|
def to_json(self, indent=2):
""" Return self formatted as JSON. """
return json.dumps(self, default=json_encode_for_printing, indent=indent)
|
https://github.com/facetoe/zenpy/blob/34c54c7e408b9ed01604ddf8b3422204c8bf31ea/zenpy/lib/api_objects/__init__.py#L52-L54
|
pretty print json
|
python
|
def _xml_pretty_print(self, data):
"""Pretty print xml data
"""
raw_string = xtree.tostring(data, 'utf-8')
parsed_string = minidom.parseString(raw_string)
return parsed_string.toprettyxml(indent='\t')
|
https://github.com/josuebrunel/myql/blob/891bad29cc83a81b3f5ebc4d0401d6f2c22f119e/myql/contrib/table/table.py#L33-L38
|
pretty print json
|
python
|
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
|
https://github.com/exoscale/cs/blob/3a0b05559c1f9f3c5bda34920d4497dfd8b9290a/cs/__init__.py#L35-L44
|
pretty print json
|
python
|
def write_pretty_dict_str(out, obj, indent=2):
"""writes JSON indented representation of `obj` to `out`"""
json.dump(obj,
out,
indent=indent,
sort_keys=True,
separators=(',', ': '),
ensure_ascii=False,
encoding="utf-8")
|
https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/utility/input_output.py#L87-L95
|
pretty print json
|
python
|
def pretty_dump(fn):
"""
Decorator used to output prettified JSON.
``response.content_type`` is set to ``application/json; charset=utf-8``.
Args:
fn (fn pointer): Function returning any basic python data structure.
Returns:
str: Data converted to prettified JSON.
"""
@wraps(fn)
def pretty_dump_wrapper(*args, **kwargs):
response.content_type = "application/json; charset=utf-8"
return json.dumps(
fn(*args, **kwargs),
# sort_keys=True,
indent=4,
separators=(',', ': ')
)
return pretty_dump_wrapper
|
https://github.com/Bystroushaak/bottle-rest/blob/428ef68a632ac092cdd49e2f03a664dbaccb0b86/src/bottle_rest/__init__.py#L22-L46
|
pretty print json
|
python
|
def json(value, pretty=True):
"""
convert value to JSON
:param value:
:param pretty:
:return:
"""
if not _Duration:
_late_import()
return _json_encoder(value, pretty=pretty)
|
https://github.com/klahnakoski/mo-logs/blob/0971277ac9caf28a755b766b70621916957d4fea/mo_logs/strings.py#L171-L180
|
pretty print json
|
python
|
def pretty(obj, verbose=False, max_width=79, newline='\n'):
"""
Pretty print the object's representation.
"""
stream = StringIO()
printer = RepresentationPrinter(stream, verbose, max_width, newline)
printer.pretty(obj)
printer.flush()
return stream.getvalue()
|
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/pretty.py#L121-L129
|
pretty print json
|
python
|
def display_pretty(*objs, **kwargs):
"""Display the pretty (default) representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw text data to
display.
raw : bool
Are the data objects raw data or Python objects that need to be
formatted before display? [default: False]
"""
raw = kwargs.pop('raw',False)
if raw:
for obj in objs:
publish_pretty(obj)
else:
display(*objs, include=['text/plain'])
|
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/display.py#L67-L84
|
pretty print json
|
python
|
def prettyprint(d):
"""Print dicttree in Json-like format. keys are sorted
"""
print(json.dumps(d, sort_keys=True,
indent=4, separators=("," , ": ")))
|
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L378-L382
|
pretty print json
|
python
|
def pretty_print(self, warnings=False):
"""
Pretty print warnings and errors.
:param bool warnings: if ``True``, also print warnings.
:rtype: string
"""
msg = []
if (warnings) and (len(self.warnings) > 0):
msg.append(u"Warnings:")
for warning in self.warnings:
msg.append(u" %s" % warning)
if len(self.errors) > 0:
msg.append(u"Errors:")
for error in self.errors:
msg.append(u" %s" % error)
return u"\n".join(msg)
|
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L670-L686
|
pretty print json
|
python
|
def _repr_pretty_(self, p, cycle):
"""
Makes JSON-serializable objects play nice with IPython's default
pretty-printer.
Sadly, :py:func:`pprint.pprint` does not have a similar
mechanism.
References:
- http://ipython.readthedocs.io/en/stable/api/generated/IPython.lib.pretty.html
- :py:meth:`IPython.lib.pretty.RepresentationPrinter.pretty`
- :py:func:`pprint._safe_repr`
"""
class_name = type(self).__name__
if cycle:
p.text('{cls}(...)'.format(
cls=class_name,
))
else:
with p.group(
len(class_name) + 1,
'{cls}('.format(cls=class_name),
')',
):
prepared = self.as_json_compatible()
if isinstance(prepared, Mapping):
p.text('**')
elif isinstance(prepared, Iterable):
p.text('*')
p.pretty(prepared)
|
https://github.com/iotaledger/iota.lib.py/blob/97cdd1e241498446b46157b79b2a1ea2ec6d387a/iota/json.py#L30-L63
|
pretty print json
|
python
|
def to_json(obj, pretty=False):
"""Converts an object to JSON, using the defaults specified in register_json_default.
:obj: the object to convert to JSON
:pretty: if True, extra whitespace is added to make the output easier to read
"""
sort_keys = False
indent = None
separators = (",", ":")
if isinstance(pretty, tuple):
sort_keys, indent, separators = pretty
elif pretty is True:
sort_keys = True
indent = 2
separators = (", ", ": ")
return json.dumps(obj, sort_keys=sort_keys, indent=indent, separators=separators,
default=json_default)
|
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/__init__.py#L78-L96
|
pretty print json
|
python
|
def pretty_print(d, ind='', verbosity=0):
"""Pretty print a data dictionary from the bridge client
"""
assert isinstance(d, dict)
for k, v in sorted(d.items()):
str_base = '{} - [{}] {}'.format(ind, type(v).__name__, k)
if isinstance(v, dict):
print(str_base.replace('-', '+', 1))
pretty_print(v, ind=ind+' ', verbosity=verbosity)
continue
elif isinstance(v, np.ndarray):
node = '{}, {}, {}'.format(str_base, v.dtype, v.shape)
if verbosity >= 2:
node += '\n{}'.format(v)
elif isinstance(v, Sequence):
if v and isinstance(v, (list, tuple)):
itemtype = ' of ' + type(v[0]).__name__
pos = str_base.find(']')
str_base = str_base[:pos] + itemtype + str_base[pos:]
node = '{}, {}'.format(str_base, v)
if verbosity < 1 and len(node) > 80:
node = node[:77] + '...'
else:
node = '{}, {}'.format(str_base, v)
print(node)
|
https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/cli/glimpse.py#L143-L168
|
pretty print json
|
python
|
def echo_json_response(response, pretty, limit=None, ndjson=False):
'''Wrapper to echo JSON with optional 'pretty' printing. If pretty is not
provided explicity and stdout is a terminal (and not redirected or piped),
the default will be to indent and sort keys'''
indent = None
sort_keys = False
nl = False
if not ndjson and (pretty or (pretty is None and sys.stdout.isatty())):
indent = 2
sort_keys = True
nl = True
try:
if ndjson and hasattr(response, 'items_iter'):
items = response.items_iter(limit)
for item in items:
click.echo(json.dumps(item))
elif not ndjson and hasattr(response, 'json_encode'):
response.json_encode(click.get_text_stream('stdout'), limit=limit,
indent=indent, sort_keys=sort_keys)
else:
res = response.get_raw()
res = json.dumps(json.loads(res), indent=indent,
sort_keys=sort_keys)
click.echo(res)
if nl:
click.echo()
except IOError as ioe:
# hide scary looking broken pipe stack traces
raise click.ClickException(str(ioe))
|
https://github.com/planetlabs/planet-client-python/blob/1c62ce7d416819951dddee0c22068fef6d40b027/planet/scripts/util.py#L136-L164
|
pretty print json
|
python
|
def _get_pretty_string(obj):
"""Return a prettier version of obj
Parameters
----------
obj : object
Object to pretty print
Returns
-------
s : str
Pretty print object repr
"""
sio = StringIO()
pprint.pprint(obj, stream=sio)
return sio.getvalue()
|
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/computation/scope.py#L63-L78
|
pretty print json
|
python
|
def pretty_dumps(data):
"""Return json string in pretty format.
**中文文档**
将字典转化成格式化后的字符串。
"""
try:
return json.dumps(data, sort_keys=True, indent=4, ensure_ascii=False)
except:
return json.dumps(data, sort_keys=True, indent=4, ensure_ascii=True)
|
https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/js.py#L269-L279
|
pretty print json
|
python
|
def to_json(value, pretty=False):
"""
Serializes the given value to JSON.
:param value: the value to serialize
:param pretty:
whether or not to format the output in a more human-readable way; if
not specified, defaults to ``False``
:type pretty: bool
:rtype: str
"""
options = {
'sort_keys': False,
'cls': BasicJSONEncoder,
}
if pretty:
options['indent'] = 2
options['separators'] = (',', ': ')
return json.dumps(value, **options)
|
https://github.com/jayclassless/basicserial/blob/da779edd955ba1009d14fae4e5926e29ad112b9d/src/basicserial/__init__.py#L80-L100
|
pretty print json
|
python
|
def pretty_print(self, printer: Optional[Printer] = None, align: int = ALIGN_CENTER, border: bool = False):
"""
Pretty prints the table.
:param printer: The printer to print with.
:param align: The alignment of the cells(Table.ALIGN_CENTER/ALIGN_LEFT/ALIGN_RIGHT)
:param border: Whether to add a border around the table
"""
if printer is None:
printer = get_printer()
table_string = self._get_pretty_table(indent=printer.indents_sum, align=align, border=border).get_string()
if table_string != '':
first_line = table_string.splitlines()[0]
first_line_length = len(first_line) - len(re.findall(Printer._ANSI_REGEXP, first_line)) * \
Printer._ANSI_COLOR_LENGTH
if self.title_align == self.ALIGN_CENTER:
title = '{}{}'.format(' ' * (first_line_length // 2 - len(self.title) // 2), self.title)
elif self.title_align == self.ALIGN_LEFT:
title = self.title
else:
title = '{}{}'.format(' ' * (first_line_length - len(self.title)), self.title)
printer.write_line(printer.YELLOW + title)
# We split the table to lines in order to keep the indentation.
printer.write_line(table_string)
|
https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/table.py#L44-L67
|
pretty print json
|
python
|
def ppj(json_data):
"""ppj
:param json_data: dictionary to print
"""
return str(json.dumps(
json_data,
sort_keys=True,
indent=4,
separators=(',', ': ')))
|
https://github.com/jay-johnson/antinex-client/blob/850ba2a2fe21c836e071def618dcecc9caf5d59c/antinex_client/utils.py#L41-L50
|
pretty print json
|
python
|
def to_json(data, pretty):
"""
Converts object to JSON formatted string with typeToken adapter
:param data: A dictionary to convert to JSON string
:param pretty: A boolean deciding whether or not to pretty format the JSON string
:return: The JSON string
"""
if pretty:
return json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
return json.dumps(data)
|
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/utils/json_utils.py#L6-L15
|
pretty print json
|
python
|
def pretty_print(self, carrot=True):
"""Print the previous and current line with line numbers and
a carret under the current character position.
Will also print a message if one is given to this exception.
"""
output = ['\n']
output.extend([line.pretty_print() for line in
self.partpyobj.get_surrounding_lines(1, 0)])
if carrot:
output.append('\n' +
(' ' * (self.partpyobj.col + 5)) + '^' + '\n')
if self.partpymsg:
output.append(self.partpymsg)
return ''.join(output)
|
https://github.com/Nekroze/partpy/blob/dbb7d2fb285464fc43d85bc31f5af46192d301f6/partpy/partpyerror.py#L17-L33
|
pretty print json
|
python
|
def printer(data):
"""
response is json or straight text.
:param data:
:return:
"""
data = str(data) # Get rid of unicode
if not isinstance(data, str):
output = json.dumps(
data,
sort_keys=True,
indent=4,
separators=(',', ': ')
)
elif hasattr(data, 'json'):
output = data.json()
else:
output = data
sys.stdout.write(output)
sys.stdout.write('\n')
sys.stdout.flush()
return
|
https://github.com/TDG-Platform/cloud-harness/blob/1d8f972f861816b90785a484e9bec5bd4bc2f569/gbdx_cloud_harness/utils/printer.py#L5-L27
|
pretty print json
|
python
|
def jsonify(data, pretty=False, **kwargs):
"""Serialize Python objects to JSON with optional 'pretty' formatting
Raises:
TypeError: from :mod:`json` lib
ValueError: from :mod:`json` lib
JSONDecodeError: from :mod:`json` lib
"""
isod = isinstance(data, OrderedDict)
params = {
'for_json': True,
'default': _complex_encode,
}
if pretty:
params['indent'] = 2
params['sort_keys'] = False if isod else True
params.update(kwargs)
try:
return json.dumps(data, ensure_ascii=False, **params)
except UnicodeDecodeError:
return json.dumps(data, **params)
|
https://github.com/neuroticnerd/armory/blob/d37c5ca1dbdd60dddb968e35f0bbe4bc1299dca1/armory/serialize.py#L15-L35
|
pretty print json
|
python
|
def get_json(self, prettyprint=False, translate=True):
"""
Get the data in JSON form
"""
j = []
if translate:
d = self.get_translated_data()
else:
d = self.data
for k in d:
j.append(d[k])
if prettyprint:
j = json.dumps(j, indent=2, separators=(',',': '))
else:
j = json.dumps(j)
return j
|
https://github.com/zwischenloesung/ardu-report-lib/blob/51bd4a07e036065aafcb1273b151bea3fdfa50fa/libardurep/datastore.py#L190-L205
|
pretty print json
|
python
|
def to_json(self, pretty=True):
"""
to_json will call to_dict then dumps into json format
"""
data_dict = self.to_dict()
if pretty:
return json.dumps(
data_dict, sort_keys=True, indent=2)
return json.dumps(data_dict, sort_keys=True)
|
https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/message.py#L150-L158
|
pretty print json
|
python
|
def pretty_print(self):
"""
Return the message as a formatted string.
:return: the string representing the message
"""
msg = "Source: " + str(self._source) + "\n"
msg += "Destination: " + str(self._destination) + "\n"
inv_types = {v: k for k, v in defines.Types.items()}
msg += "Type: " + str(inv_types[self._type]) + "\n"
msg += "MID: " + str(self._mid) + "\n"
if self._code is None:
self._code = 0
msg += "Code: " + str(defines.Codes.LIST[self._code].name) + "\n"
msg += "Token: " + str(self._token) + "\n"
for opt in self._options:
msg += str(opt)
msg += "Payload: " + "\n"
msg += str(self._payload) + "\n"
return msg
|
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L675-L695
|
pretty print json
|
python
|
def output_json(gandi, format, value):
""" Helper to show json output """
if format == 'json':
gandi.echo(json.dumps(value, default=date_handler, sort_keys=True))
elif format == 'pretty-json':
gandi.echo(json.dumps(value, default=date_handler, sort_keys=True,
indent=2, separators=(',', ': ')))
|
https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/utils/__init__.py#L465-L471
|
pretty print json
|
python
|
def pretty(self, obj):
"""Pretty print the given object."""
obj_id = id(obj)
cycle = obj_id in self.stack
self.stack.append(obj_id)
self.begin_group()
try:
obj_class = getattr(obj, '__class__', None) or type(obj)
# First try to find registered singleton printers for the type.
try:
printer = self.singleton_pprinters[obj_id]
except (TypeError, KeyError):
pass
else:
return printer(obj, self, cycle)
# Next walk the mro and check for either:
# 1) a registered printer
# 2) a _repr_pretty_ method
for cls in _get_mro(obj_class):
if cls in self.type_pprinters:
# printer registered in self.type_pprinters
return self.type_pprinters[cls](obj, self, cycle)
else:
# deferred printer
printer = self._in_deferred_types(cls)
if printer is not None:
return printer(obj, self, cycle)
else:
# Finally look for special method names.
# Some objects automatically create any requested
# attribute. Try to ignore most of them by checking for
# callability.
if '_repr_pretty_' in obj_class.__dict__:
meth = obj_class._repr_pretty_
if callable(meth):
return meth(obj, self, cycle)
return _default_pprint(obj, self, cycle)
finally:
self.end_group()
self.stack.pop()
|
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/pretty.py#L324-L363
|
pretty print json
|
python
|
def pretty_print(self, printer: Optional[Printer] = None, min_width: int = 1, min_unit_width: int = 1):
"""
Prints the file size (and it's unit), reserving places for longer sizes and units.
For example:
min_unit_width = 1:
793 B
100 KB
min_unit_width = 2:
793 B
100 KB
min_unit_width = 3:
793 B
100 KB
"""
unit, unit_divider = self._unit_info()
unit_color = self.SIZE_COLORS[unit]
# Multiply and then divide by 100 in order to have only two decimal places.
size_in_unit = (self.size * 100) / unit_divider / 100
# Add spaces to align the units.
unit = '{}{}'.format(' ' * (min_unit_width - len(unit)), unit)
size_string = f'{size_in_unit:.1f}'
total_len = len(size_string) + 1 + len(unit)
if printer is None:
printer = get_printer()
spaces_count = min_width - total_len
if spaces_count > 0:
printer.write(' ' * spaces_count)
printer.write(f'{size_string} {unit_color}{unit}')
|
https://github.com/ofir123/py-printer/blob/876c83b32120f3b6a7b06989b2cd9b86915d1a50/pyprinter/file_size.py#L208-L235
|
pretty print json
|
python
|
def read_json(file_path):
""" Read in a json file and return a dictionary representation """
try:
with open(file_path, 'r') as f:
config = json_tricks.load(f)
except ValueError:
print(' '+'!'*58)
print(' Woops! Looks the JSON syntax is not valid in:')
print(' {}'.format(file_path))
print(' Note: commonly this is a result of having a trailing comma \n in the file')
print(' '+'!'*58)
raise
return config
|
https://github.com/LIVVkit/LIVVkit/blob/680120cd437e408673e62e535fc0a246c7fc17db/livvkit/util/functions.py#L136-L149
|
pretty print json
|
python
|
def json_format_dict(self, data, pretty=False):
''' Converts a dict to a JSON object and dumps it as a formatted
string '''
if pretty:
return json.dumps(data, sort_keys=True, indent=2)
else:
return json.dumps(data)
|
https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/client/loomengine/playbooks/gce.py#L465-L472
|
pretty print json
|
python
|
def pprint(obj, *args, **kwargs):
"""Pretty-printing function that can pretty-print OrderedDicts
like regular dictionaries. Useful for printing the output of
:meth:`marshmallow.Schema.dump`.
"""
if isinstance(obj, collections.OrderedDict):
print(json.dumps(obj, *args, **kwargs))
else:
py_pprint(obj, *args, **kwargs)
|
https://github.com/marshmallow-code/marshmallow/blob/a6b6c4151f1fbf16f3774d4052ca2bddf6903750/src/marshmallow/utils.py#L86-L94
|
pretty print json
|
python
|
def output_raw(self, text):
"""
Output results in raw JSON format
"""
payload = json.loads(text)
out = json.dumps(payload, sort_keys=True, indent=self._indent, separators=(',', ': '))
print(self.colorize_json(out))
|
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/measurement_get.py#L194-L200
|
pretty print json
|
python
|
def serialize_to_normalized_pretty_json(py_obj):
"""Serialize a native object to normalized, pretty printed JSON.
The JSON string is normalized by sorting any dictionary keys.
Args:
py_obj: object
Any object that can be represented in JSON. Some types, such as datetimes are
automatically converted to strings.
Returns:
str: normalized, pretty printed JSON string.
"""
return json.dumps(py_obj, sort_keys=True, indent=2, cls=ToJsonCompatibleTypes)
|
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/util.py#L287-L301
|
pretty print json
|
python
|
def ppjson(dumpit: Any, elide_to: int = None) -> str:
"""
JSON pretty printer, whether already json-encoded or not
:param dumpit: object to pretty-print
:param elide_to: optional maximum length including ellipses ('...')
:return: json pretty-print
"""
if elide_to is not None:
elide_to = max(elide_to, 3) # make room for ellipses '...'
try:
rv = json.dumps(json.loads(dumpit) if isinstance(dumpit, str) else dumpit, indent=4)
except TypeError:
rv = '{}'.format(pformat(dumpit, indent=4, width=120))
return rv if elide_to is None or len(rv) <= elide_to else '{}...'.format(rv[0 : elide_to - 3])
|
https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/frill.py#L30-L45
|
pretty print json
|
python
|
def pretty_print(self):
"""
Pretty print representation of this fragment,
as ``(identifier, begin, end, text)``.
:rtype: string
.. versionadded:: 1.7.0
"""
return u"%s\t%.3f\t%.3f\t%s" % (
(self.identifier or u""),
(self.begin if self.begin is not None else TimeValue("-2.000")),
(self.end if self.end is not None else TimeValue("-1.000")),
(self.text or u"")
)
|
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragment.py#L204-L218
|
pretty print json
|
python
|
def format_json(json_object, indent):
""" Pretty-format json data """
indent_str = "\n" + " " * indent
json_str = json.dumps(json_object, indent=2, default=serialize_json_var)
return indent_str.join(json_str.split("\n"))
|
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/output.py#L55-L59
|
pretty print json
|
python
|
def print_data(data):
"""Prints object key-value pairs in a custom format
:param data: The dict to print
:type data: dict
:rtype: None
"""
print(", ".join(["{}=>{}".format(key, value) for key, value in data]))
|
https://github.com/palantir/typedjsonrpc/blob/274218fcd236ff9643506caa629029c9ba25a0fb/contrib/multi-module-example/typedjsonrpc_example/valid.py#L65-L72
|
pretty print json
|
python
|
def pretty_print(self, indent=0):
"""Print the document without tags using indentation
"""
s = tab = ' '*indent
s += '%s: ' %self.tag
if isinstance(self.value, basestring):
s += self.value
else:
s += '\n'
for e in self.value:
s += e.pretty_print(indent+4)
s += '\n'
return s
|
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/extras/xml_tools.py#L202-L216
|
pretty print json
|
python
|
def outputjson(self, obj):
"""
Serialize `obj` with JSON and output to the client
"""
self.header('Content-Type', 'application/json')
self.outputdata(json.dumps(obj).encode('ascii'))
|
https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/utils/http.py#L567-L572
|
pretty print json
|
python
|
def pretty_print(session, feed):
"""
Print the dictionary entry of a feed in a nice way.
"""
if feed in session.feeds:
print()
feed_info = os.path.join(session.data_dir, feed)
entrylinks, linkdates = parse_feed_info(feed_info)
print(feed)
print("-"*len(feed))
print(''.join([" url: ", session.feeds[feed]["url"]]))
if linkdates != []:
print(''.join([" Next sync will download from: ", time.strftime(
"%d %b %Y %H:%M:%S", tuple(max(linkdates))), "."]))
else:
print("You don't have a feed called {}.".format(feed), file=sys.stderr,
flush=True)
|
https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/aux_functions.py#L255-L271
|
pretty print json
|
python
|
def pretty(d, indent=0):
"""A prettier way to print nested dicts
"""
for key, value in d.items():
print(' ' * indent + str(key))
if isinstance(value, dict):
pretty(value, indent+1)
else:
sys.stderr.write(' ' * (indent+1) + str(value) + '\n')
|
https://github.com/kblin/ncbi-genome-download/blob/dc55382d351c29e1027be8fa3876701762c1d752/contrib/gimme_taxa.py#L85-L93
|
pretty print json
|
python
|
def __obj2json(self, obj):
"""Serialize obj to a JSON formatted string.
This is useful for pretty printing log records in the console.
"""
return json.dumps(obj, indent=self._indent, sort_keys=self._sort_keys)
|
https://github.com/vmig/pylogrus/blob/4f3a66033adaa94c83967e5bec37595948bdedfb/pylogrus/json_formatter.py#L79-L84
|
pretty print json
|
python
|
def pretty_print_head(dict_, count=10): #TODO only format and rename to pretty_head
'''
Pretty print some items of a dict.
For an unordered dict, ``count`` arbitrary items will be printed.
Parameters
----------
dict_ : ~typing.Dict
Dict to print from.
count : int
Number of items to print.
Raises
------
ValueError
When ``count < 1``.
'''
if count < 1:
raise ValueError('`count` must be at least 1')
pprint(dict(take(count, dict_.items())))
|
https://github.com/timdiels/pytil/blob/086a3f8d52caecdd9d1c9f66c8d8a6d38667b00b/pytil/dict.py#L26-L46
|
pretty print json
|
python
|
def pprint(object, stream=None, indent=1, width=80, depth=None):
"""Pretty-print a Python object to a stream [default is sys.stdout]."""
printer = PrettyPrinter(
stream=stream, indent=indent, width=width, depth=depth)
printer.pprint(object)
|
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/pprint.py#L54-L58
|
pretty print json
|
python
|
def pretty_print(self, as_list=False, show_datetime=True):
"""
Return a Unicode string pretty print of the log entries.
:param bool as_list: if ``True``, return a list of Unicode strings,
one for each entry, instead of a Unicode string
:param bool show_datetime: if ``True``, show the date and time of the entries
:rtype: string or list of strings
"""
ppl = [entry.pretty_print(show_datetime) for entry in self.entries]
if as_list:
return ppl
return u"\n".join(ppl)
|
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/logger.py#L130-L142
|
pretty print json
|
python
|
def emphasis(obj, align=True):
''' Clearer data printing '''
if isinstance(obj, dict):
if align:
pretty_msg = os.linesep.join(
["%25s: %s" % (k, obj[k]) for k in sorted(obj.keys())])
else:
pretty_msg = json.dumps(obj, indent=4, sort_keys=True)
else:
return obj
return pretty_msg
|
https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/debug.py#L28-L38
|
pretty print json
|
python
|
def print_callback(msg):
"""Print callback, prints message to stdout as JSON in one line."""
json.dump(msg, stdout)
stdout.write('\n')
stdout.flush()
|
https://github.com/CyberInt/dockermon/blob/a8733b9395cb1b551971f17c31d7f4a8268bb969/dockermon.py#L109-L113
|
pretty print json
|
python
|
def render(file):
"""Pretty print the JSON file for rendering."""
with file.open() as fp:
encoding = detect_encoding(fp, default='utf-8')
file_content = fp.read().decode(encoding)
json_data = json.loads(file_content, object_pairs_hook=OrderedDict)
return json.dumps(json_data, indent=4, separators=(',', ': '))
|
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/json_prismjs.py#L23-L29
|
pretty print json
|
python
|
def to_json(obj):
"""Return a json string representing the python object obj."""
i = StringIO.StringIO()
w = Writer(i, encoding='UTF-8')
w.write_value(obj)
return i.getvalue()
|
https://github.com/niligulmohar/python-symmetric-jsonrpc/blob/f0730bef5c19a1631d58927c0f13d29f16cd1330/symmetricjsonrpc/json.py#L37-L42
|
pretty print json
|
python
|
def pretty_print_str(self):
'''
Create a string to pretty-print this trie to standard output.
'''
retval = ''
# dfs
todo = [self.root]
while todo:
current = todo.pop()
for char in reversed(sorted(current.keys())):
todo.append(current[char])
indent = ' ' * (current.depth * 2)
retval += indent + current.__unicode__() + '\n'
return retval.rstrip('\n')
|
https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/ahocorasick.py#L147-L160
|
pretty print json
|
python
|
def to_json(self):
"""
Convert to a json-serializable representation.
Returns:
dict: A dict representation that is json-serializable.
"""
return {
"xblock_id": six.text_type(self.xblock_id),
"messages": [message.to_json() for message in self.messages],
"empty": self.empty
}
|
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/validation.py#L111-L122
|
pretty print json
|
python
|
def data_json(self, pretty=False):
"""Returns the data as a valid JSON string."""
if pretty:
return json.dumps(self.data, sort_keys=True, indent=4, separators=(',', ': '))
else:
return json.dumps(self.data)
|
https://github.com/aparsons/threadfix_api/blob/76fd1bd26e9ac863636112cd30d733543807ff7d/threadfix_api/threadfix.py#L409-L414
|
pretty print json
|
python
|
def json(self):
"""
Serializes json text stream into python dictionary.
:return dict: json
"""
_json = json.loads(self.reader)
if _json.get('error', None):
raise HTTPError(_json['error']['errors'])
return _json
|
https://github.com/jjangsangy/kan/blob/7da9d9ec5dc6b8bbb86cfd27d737978a406d9fa6/kan/structures.py#L150-L159
|
pretty print json
|
python
|
def json(self, *, # type: ignore
loads: Callable[[Any], Any]=json.loads) -> None:
"""Return parsed JSON data.
.. versionadded:: 0.22
"""
return loads(self.data)
|
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/http_websocket.py#L85-L91
|
pretty print json
|
python
|
def _repr_pretty_(self, p, cycle):
"""method that defines ``Struct``'s pretty printing rules for iPython
Args:
p (IPython.lib.pretty.RepresentationPrinter): pretty printer object
cycle (bool): is ``True`` if pretty detected a cycle
"""
if cycle:
p.text('Struct(...)')
else:
with p.group(7, 'Struct(', ')'):
p.pretty(self._asdict())
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/configs/__init__.py#L56-L67
|
pretty print json
|
python
|
def json_as_html(self):
""" Print out self.json in a nice way. """
# To avoid circular import
from cspreports import utils
formatted_json = utils.format_report(self.json)
return mark_safe("<pre>\n%s</pre>" % escape(formatted_json))
|
https://github.com/adamalton/django-csp-reports/blob/867992c6f535cf6afbf911f92af7eea4c61e4b73/cspreports/models.py#L161-L168
|
pretty print json
|
python
|
def to_json(self):
"""Return a JSON-serializable representation."""
return {
'tpm': self.tpm,
'cm': self.cm,
'size': self.size,
'node_labels': self.node_labels
}
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/network.py#L198-L205
|
pretty print json
|
python
|
def to_pretty(self, format='str'):
"""Return a string with a prettified version of this object’s contents.
The format is a multiline string where each line is of the form ``key
= value``. If the *format* argument is equal to ``"str"``, each
``value`` is the stringification of the value; if it is ``"repr"``, it
is its :func:`repr`.
Calling :func:`str` on a :class:`Holder` returns a slightly different
pretty stringification that uses a textual representation similar to a
Python :class:`dict` literal.
"""
if format == 'str':
template = '%-*s = %s'
elif format == 'repr':
template = '%-*s = %r'
else:
raise ValueError('unrecognized value for "format": %r' % format)
d = self.__dict__
maxlen = 0
for k in six.iterkeys(d):
maxlen = max(maxlen, len(k))
return '\n'.join(template % (maxlen, k, d[k])
for k in sorted(six.iterkeys(d)))
|
https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/__init__.py#L219-L246
|
pretty print json
|
python
|
def make_formatter(format_name):
"""Returns a callable that outputs the data. Defaults to print."""
if "json" in format_name:
from json import dumps
import datetime
def jsonhandler(obj): obj.isoformat() if isinstance(obj, (datetime.datetime, datetime.date)) else obj
if format_name == "prettyjson":
def jsondumps(data): return dumps(data, default=jsonhandler, indent=2, separators=(',', ': '))
else:
def jsondumps(data): return dumps(data, default=jsonhandler)
def jsonify(data):
if isinstance(data, dict):
print(jsondumps(data))
elif isinstance(data, list):
print(jsondumps([device._asdict() for device in data]))
else:
print(dumps({'result': data}))
return jsonify
else:
def printer(data):
if isinstance(data, dict):
print(data)
else:
for row in data:
print(row)
return printer
|
https://github.com/MatMaul/pynetgear/blob/247d6b9524fcee4b2da0e65ca12c52ebdd3676b2/pynetgear/__main__.py#L9-L36
|
pretty print json
|
python
|
def printy(s):
"""Python 2/3 compatible print-like function"""
if hasattr(s, 'as_utf8'):
if hasattr(sys.stdout, 'buffer'):
sys.stdout.buffer.write(s.as_utf8)
sys.stdout.buffer.write(b"\n")
else:
sys.stdout.write(s.as_utf8)
sys.stdout.write(b"\n")
else:
print(s)
|
https://github.com/jart/fabulous/blob/19903cf0a980b82f5928c3bec1f28b6bdd3785bd/fabulous/compatibility.py#L20-L30
|
pretty print json
|
python
|
def pretty_print(self):
"""Use `PrettyTable` to perform formatted outprint."""
pt = PrettyTable()
if len(self) == 0:
pt._set_field_names(['Sorry,'])
pt.add_row([TRAIN_NOT_FOUND])
else:
pt._set_field_names(self.headers)
for train in self.trains:
pt.add_row(train)
print(pt)
|
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/trains.py#L103-L113
|
pretty print json
|
python
|
def prt_js(js, sort_keys=True, indent=4):
"""Print Json in pretty format.
There's a standard module pprint, can pretty print python dict and list.
But it doesn't support sorted key. That why we need this func.
Usage::
>>> from weatherlab.lib.dataIO.js import prt_js
>>> prt_js({"a": 1, "b": 2})
{
"a": 1,
"b": 2
}
**中文文档**
以人类可读的方式打印可Json化的Python对象。
"""
print(js2str(js, sort_keys, indent))
|
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dataIO/js.py#L388-L406
|
pretty print json
|
python
|
def pretty_format_args(*args, **kwargs):
"""
Take the args, and kwargs that are passed them and format in a
prototype style.
"""
args = list([repr(a) for a in args])
for key, value in kwargs.items():
args.append("%s=%s" % (key, repr(value)))
return "(%s)" % ", ".join([a for a in args])
|
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/exception.py#L16-L24
|
pretty print json
|
python
|
def pretty_print_config_to_json(self, services, hostname=None):
"""JSON string description of a protorpc.remote.Service in API format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
string, The API descriptor document as a JSON string.
"""
descriptor = self.get_config_dict(services, hostname)
return json.dumps(descriptor, sort_keys=True, indent=2,
separators=(',', ': '))
|
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config.py#L2248-L2262
|
pretty print json
|
python
|
def pretty_print(self, objlist):
'''Pretty print the result of s3walk. Here we calculate the maximum width
of each column and align them.
'''
def normalize_time(timestamp):
'''Normalize the timestamp format for pretty print.'''
if timestamp is None:
return ' ' * 16
return TIMESTAMP_FORMAT % (timestamp.year, timestamp.month, timestamp.day, timestamp.hour, timestamp.minute)
cwidth = [0, 0, 0]
format = '%%%ds %%%ds %%-%ds'
# Calculate maximum width for each column.
result = []
for obj in objlist:
last_modified = normalize_time(obj['last_modified'])
size = str(obj['size']) if not obj['is_dir'] else 'DIR'
name = obj['name']
item = (last_modified, size, name)
for i, value in enumerate(item):
if cwidth[i] < len(value):
cwidth[i] = len(value)
result.append(item)
# Format output.
for item in result:
text = (format % tuple(cwidth)) % item
message('%s', text.rstrip())
|
https://github.com/bloomreach/s4cmd/blob/bb51075bf43703e7cd95aa39288cf7732ec13a6d/s4cmd.py#L1592-L1622
|
pretty print json
|
python
|
def to_json(self, include_body=False):
"""Exports the object to a JSON friendly dict
Args:
include_body (bool): Include the body of the message in the output
Returns:
Dict representation of object type
"""
message = {
'emailId': self.email_id,
'timestamp': isoformat(self.timestamp),
'subsystem': self.subsystem,
'subject': self.subject,
'sender': self.sender,
'recipients': self.recipients,
'uuid': self.uuid,
'messageHtml': None,
'messageText': None
}
if include_body:
message['messageHtml'] = self.message_html
message['messageText'] = self.message_text
return message
|
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/schema/base.py#L135-L161
|
pretty print json
|
python
|
def serialize_json(obj, pretty=None, indent=None, **kwargs):
''' Return a serialized JSON representation of objects, suitable to
send to BokehJS.
This function is typically used to serialize single python objects in
the manner expected by BokehJS. In particular, many datetime values are
automatically normalized to an expected format. Some Bokeh objects can
also be passed, but note that Bokeh models are typically properly
serialized in the context of an entire Bokeh document.
The resulting JSON always has sorted keys. By default. the output is
as compact as possible unless pretty output or indentation is requested.
Args:
obj (obj) : the object to serialize to JSON format
pretty (bool, optional) :
Whether to generate prettified output. If ``True``, spaces are
added after added after separators, and indentation and newlines
are applied. (default: False)
Pretty output can also be enabled with the environment variable
``BOKEH_PRETTY``, which overrides this argument, if set.
indent (int or None, optional) :
Amount of indentation to use in generated JSON output. If ``None``
then no indentation is used, unless pretty output is enabled,
in which case two spaces are used. (default: None)
Any additional keyword arguments are passed to ``json.dumps``, except for
some that are computed internally, and cannot be overridden:
* allow_nan
* indent
* separators
* sort_keys
Examples:
.. code-block:: python
>>> data = dict(b=np.datetime64('2017-01-01'), a = np.arange(3))
>>>print(serialize_json(data))
{"a":[0,1,2],"b":1483228800000.0}
>>> print(serialize_json(data, pretty=True))
{
"a": [
0,
1,
2
],
"b": 1483228800000.0
}
'''
# these args to json.dumps are computed internally and should not be passed along
for name in ['allow_nan', 'separators', 'sort_keys']:
if name in kwargs:
raise ValueError("The value of %r is computed internally, overriding is not permissable." % name)
if pretty is None:
pretty = settings.pretty(False)
if pretty:
separators=(",", ": ")
else:
separators=(",", ":")
if pretty and indent is None:
indent = 2
return json.dumps(obj, cls=BokehJSONEncoder, allow_nan=False, indent=indent, separators=separators, sort_keys=True, **kwargs)
|
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/json_encoder.py#L85-L161
|
pretty print json
|
python
|
def _format_args():
"""Get JSON dump indentation and separates."""
# Ensure we can run outside a application/request context.
try:
pretty_format = \
current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and \
not request.is_xhr
except RuntimeError:
pretty_format = False
if pretty_format:
return dict(
indent=2,
separators=(', ', ': '),
)
else:
return dict(
indent=None,
separators=(',', ':'),
)
|
https://github.com/inveniosoftware/invenio-communities/blob/5c4de6783724d276ae1b6dd13a399a9e22fadc7a/invenio_communities/serializers/response.py#L36-L55
|
pretty print json
|
python
|
def to_json(self, depth=-1, **kwargs):
"""Returns a JSON representation of the object."""
return json.dumps(self.to_dict(depth=depth, ordered=True), **kwargs)
|
https://github.com/python-visualization/branca/blob/4e89e88a5a7ff3586f0852249c2c125f72316da8/branca/element.py#L138-L140
|
pretty print json
|
python
|
def pretty_render(data, format='text', indent=0):
"""
Render a dict based on a format
"""
if format == 'json':
return render_json(data)
elif format == 'html':
return render_html(data)
elif format == 'xml':
return render_xml(data)
else:
return dict_to_plaintext(data, indent=indent)
|
https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/text.py#L263-L274
|
pretty print json
|
python
|
def prettify_json(json_string):
"""Given a JSON string, it returns it as a
safe formatted HTML"""
try:
data = json.loads(json_string)
html = '<pre>' + json.dumps(data, sort_keys=True, indent=4) + '</pre>'
except:
html = json_string
return mark_safe(html)
|
https://github.com/soynatan/django-easy-audit/blob/03e05bc94beb29fc3e4ff86e313a6fef4b766b4b/easyaudit/admin_helpers.py#L21-L29
|
pretty print json
|
python
|
def _format_args():
"""Get JSON dump indentation and separates."""
if request and request.args.get('prettyprint'):
return dict(
indent=2,
separators=(', ', ': '),
)
else:
return dict(
indent=None,
separators=(',', ':'),
)
|
https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/json.py#L23-L34
|
pretty print json
|
python
|
def _write_json(obj, path): # type: (object, str) -> None
"""Writes a serializeable object as a JSON file"""
with open(path, 'w') as f:
json.dump(obj, f)
|
https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_env.py#L36-L39
|
pretty print json
|
python
|
def to_json(self):
"""Exports the object to a JSON friendly dict
Returns:
Dict representation of the object
"""
return {
'userId': self.user_id,
'username': self.username,
'roles': self.roles,
'authSystem': self.auth_system
}
|
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/schema/base.py#L370-L381
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.