编写python脚本,调试的时候需要打印json格式报文,直接打印看不出层次,可以使用json.dumps格式化打印

import json
import requests

def test_json():
  r=requests.get('https://home.testing-studio.com/categories.json')
  print(r.json())
  print(json.dumps(r.json(), indent=2,ensure_ascii=False)) # r.json()是json对象,indent表示缩进,ensure_ascii设置编码
格式化打印前:

格式化打印前:

Python json格式化打印实现过程解析

格式化打印后:

Python json格式化打印实现过程解析

json.dumps方法源码:

def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True,
    allow_nan=True, cls=None, indent=None, separators=None,
    default=None, sort_keys=False, **kw):
  """Serialize ``obj`` to a JSON formatted ``str``.

  If ``skipkeys`` is true then ``dict`` keys that are not basic types
  (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped
  instead of raising a ``TypeError``.

  If ``ensure_ascii`` is false, then the return value can contain non-ASCII
  characters if they appear in strings contained in ``obj``. Otherwise, all
  such characters are escaped in JSON strings.

  If ``check_circular`` is false, then the circular reference check
  for container types will be skipped and a circular reference will
  result in an ``OverflowError`` (or worse).

  If ``allow_nan`` is false, then it will be a ``ValueError`` to
  serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
  strict compliance of the JSON specification, instead of using the
  JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).

  If ``indent`` is a non-negative integer, then JSON array elements and
  object members will be pretty-printed with that indent level. An indent
  level of 0 will only insert newlines. ``None`` is the most compact
  representation.

  If specified, ``separators`` should be an ``(item_separator, key_separator)``
  tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and
  ``(',', ': ')`` otherwise. To get the most compact JSON representation,
  you should specify ``(',', ':')`` to eliminate whitespace.

  ``default(obj)`` is a function that should return a serializable version
  of obj or raise TypeError. The default simply raises TypeError.

  If *sort_keys* is true (default: ``False``), then the output of
  dictionaries will be sorted by key.

  To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
  ``.default()`` method to serialize additional types), specify it with
  the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.

  """
  # cached encoder
  if (not skipkeys and ensure_ascii and
    check_circular and allow_nan and
    cls is None and indent is None and separators is None and
    default is None and not sort_keys and not kw):
    return _default_encoder.encode(obj)
  if cls is None:
    cls = JSONEncoder
  return cls(
    skipkeys=skipkeys, ensure_ascii=ensure_ascii,
    check_circular=check_circular, allow_nan=allow_nan, indent=indent,
    separators=separators, default=default, sort_keys=sort_keys,
    **kw).encode(obj)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

标签:
python,json,格式化打印

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com

评论“Python json格式化打印实现过程解析”

暂无“Python json格式化打印实现过程解析”评论...

P70系列延期,华为新旗舰将在下月发布

3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。

而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?

根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。