脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python json格式化打印实现过程解析

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

2020-07-21 17:33捷后愚生 Python

这篇文章主要介绍了Python json格式化打印实现过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

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

?
1
2
3
4
5
6
7
8
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方法源码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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)

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

原文链接:https://www.cnblogs.com/Uni-Hoang/p/13336388.html

延伸 · 阅读

精彩推荐