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


Posted in Python onJuly 21, 2020

编写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 相关文章推荐
Python函数中*args和**kwargs来传递变长参数的用法
Jan 26 Python
Python装饰器实现几类验证功能做法实例
May 18 Python
python代码实现ID3决策树算法
Dec 20 Python
Python中常用的内置方法
Jan 28 Python
实例讲解Python3中abs()函数
Feb 19 Python
python 求一个列表中所有元素的乘积实例
Jun 11 Python
python中字典按键或键值排序的实现代码
Aug 27 Python
python实现tail -f 功能
Jan 17 Python
python实现图像全景拼接
Mar 27 Python
Python面向对象多态实现原理及代码实例
Sep 16 Python
python中pyqtgraph知识点总结
Jan 26 Python
pytorch分类模型绘制混淆矩阵以及可视化详解
Apr 07 Python
基于python实现删除指定文件类型
Jul 21 #Python
python打开音乐文件的实例方法
Jul 21 #Python
Python读取yaml文件的详细教程
Jul 21 #Python
Python中bisect的用法及示例详解
Jul 20 #Python
python为什么要安装到c盘
Jul 20 #Python
python如何代码集体右移
Jul 20 #Python
python接入支付宝的实例操作
Jul 20 #Python
You might like
fleaphp crud操作之findByField函数的使用方法
2011/04/23 PHP
php实现执行某一操作时弹出确认、取消对话框
2013/12/30 PHP
symfony2.4的twig中date用法分析
2016/03/18 PHP
PHP检测链接是否存在的代码实例分享
2016/05/06 PHP
thinkPHP5.0框架自动加载机制分析
2017/03/18 PHP
ThinkPHP5.0 图片上传生成缩略图实例代码说明
2018/06/20 PHP
PHP等比例压缩图片的实例代码
2018/07/26 PHP
PHP数据源架构模式之表入口模式实例分析
2020/01/23 PHP
关于JS中的闭包浅谈
2013/08/23 Javascript
jquery+html5时钟特效代码分享(可设置闹钟并且语音提醒)
2020/03/30 Javascript
js中substr,substring,indexOf,lastIndexOf,split,replace的用法详解
2015/11/09 Javascript
深入学习AngularJS中数据的双向绑定机制
2016/03/04 Javascript
详解Vue.js之视图和数据的双向绑定(v-model)
2017/06/23 Javascript
vue中计算属性(computed)、methods和watched之间的区别
2017/07/27 Javascript
基于node搭建服务器,写接口,调接口,跨域的实例
2018/05/13 Javascript
jQuery事件绑定和解绑、事件冒泡与阻止事件冒泡及弹出应用示例
2019/05/13 jQuery
深入浅析ng-bootstrap 组件集中 tabset 组件的实现分析
2019/07/19 Javascript
[01:23:24]DOTA2-DPC中国联赛 正赛 PSG.LGD vs Elephant BO3 第三场 2月7日
2021/03/11 DOTA
使用Python3中的gettext模块翻译Python源码以支持多语言
2015/03/31 Python
Python实现模拟时钟代码推荐
2015/11/08 Python
python基于phantomjs实现导入图片
2016/05/13 Python
python的变量与赋值详细分析
2017/11/08 Python
python使用RNN实现文本分类
2018/05/24 Python
Python运维自动化之nginx配置文件对比操作示例
2018/08/29 Python
Python3爬虫全国地址信息
2019/01/05 Python
详解如何管理多个Python版本和虚拟环境
2019/05/10 Python
python3 xpath和requests应用详解
2020/03/06 Python
Python读取JSON数据操作实例解析
2020/05/18 Python
python rsa-oaep加密的示例代码
2020/09/23 Python
Banana Republic英国官网:香蕉共和国,GAP集团旗下偏贵族风
2018/04/24 全球购物
实习生自我鉴定
2013/12/12 职场文书
认识深刻的检讨书
2014/02/16 职场文书
互联网电子商务专业毕业生求职信
2014/03/18 职场文书
Go 自定义package包设置与导入操作
2021/05/06 Golang
SpringBoot实现异步事件驱动的方法
2021/06/28 Java/Android
JavaScript中时间格式化新思路toLocaleString()
2021/11/07 Javascript