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 pdb调试方法分享
Jan 21 Python
让python同时兼容python2和python3的8个技巧分享
Jul 11 Python
Python六大开源框架对比
Oct 19 Python
Python双精度浮点数运算并分行显示操作示例
Jul 21 Python
python smtplib发送带附件邮件小程序
May 22 Python
python实现图像检索的三种(直方图/OpenCV/哈希法)
Aug 08 Python
Python计算指定日期是今年的第几天(三种方法)
Mar 26 Python
python获取命令行参数实例方法讲解
Nov 02 Python
python自动生成证件号的方法示例
Jan 14 Python
Ubuntu20.04环境安装tensorflow2的方法步骤
Jan 29 Python
Keras在mnist上的CNN实践,并且自定义loss函数曲线图操作
May 25 Python
Python语法学习之进程的创建与常用方法详解
Apr 08 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
当海贼王变成JOJO风
2020/03/02 日漫
使用网络地址转换实现多服务器负载均衡
2006/10/09 PHP
PHP中的CMS的涵义
2007/03/11 PHP
php5 apache 2.2 webservice 创建与配置(java)
2011/01/27 PHP
CodeIgniter框架URL路由总结
2014/09/03 PHP
在Linux系统的服务器上隐藏PHP版本号的方法
2015/06/06 PHP
PHP实现财务审核通过后返现金额到客户的功能
2019/07/04 PHP
JS面向对象、prototype、call()、apply()
2009/05/14 Javascript
收集json解析的四种方法分享
2014/01/17 Javascript
js选项卡的实现方法
2015/02/09 Javascript
jQuery插件formValidator自定义函数扩展功能实例详解
2015/11/25 Javascript
详解jquery事件delegate()的使用方法
2016/01/25 Javascript
jquery实现图片列表鼠标移入微动
2016/12/01 Javascript
JS实现焦点图轮播效果的方法详解
2016/12/19 Javascript
Vue.js仿Metronic高级表格(二)数据渲染
2017/04/19 Javascript
JavaScript实现无穷滚动加载数据
2017/05/06 Javascript
js学习总结_选项卡封装(实例讲解)
2017/07/13 Javascript
Vue2.0实现将页面中表格数据导出excel的实例
2017/08/09 Javascript
fetch 使用及如何接收JS传值
2017/11/11 Javascript
Node爬取大批量文件的方法示例
2019/06/28 Javascript
JavaScript 自定义html元素鼠标右键菜单功能
2019/12/02 Javascript
在vue中使用echarts(折线图的demo,markline用法)
2020/07/20 Javascript
[46:25]DOTA2上海特级锦标赛主赛事日 - 4 败者组第五轮 MVP.Phx VS EG第二局
2016/03/05 DOTA
pandas.DataFrame 根据条件新建列并赋值的方法
2018/04/08 Python
Python适配器模式代码实现解析
2019/08/02 Python
画pytorch模型图,以及参数计算的方法
2019/08/17 Python
一些关于python 装饰器的个人理解
2020/08/31 Python
HTML5 本地存储和内容按需加载的思路和方法
2011/04/07 HTML / CSS
全球立体声:World Wide Stereo
2018/09/29 全球购物
华为C++笔试题
2014/08/05 面试题
白血病募捐倡议书
2014/05/14 职场文书
设备技术员岗位职责
2015/04/11 职场文书
公司员工奖惩制度
2015/08/04 职场文书
幼儿园园长新年寄语
2015/08/17 职场文书
使用Oracle跟踪文件的问题详解
2021/06/28 Oracle
git中cherry-pick命令的使用教程
2022/06/25 Servers