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

编写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设置编码
格式化打印前:

格式化打印前:

格式化打印后:

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)

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

(0)

相关推荐

  • python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换)

    python3 json数据格式的转换(dumps/loads的使用.dict to str/str to dict.json字符串/字典的相互转换) Python3 JSON 数据解析 JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式.它基于ECMAScript的一个子集. Python3 中可以使用 json 模块来对 JSON 数据进行编解码,它包含了两个函数: json.dumps(): 对数据进行编码. json.loads(): 对数据进

  • 对python requests发送json格式数据的实例详解

    requests是常用的请求库,不管是写爬虫脚本,还是测试接口返回数据等.都是很简单常用的工具. 这里就记录一下如何用requests发送json格式的数据,因为一般我们post参数,都是直接post,没管post的数据的类型,它默认有一个类型的,貌似是 application/x-www-form-urlencoded. 但是,我们写程序的时候,最常用的接口post数据的格式是json格式.当我们需要post json格式数据的时候,怎么办呢,只需要添加修改两处小地方即可. 详见如下代码: i

  • 利用python将json数据转换为csv格式的方法

    假设.json文件中存储的数据为: {"type": "Point", "link": "http://www.dianping.com/newhotel/22416995", "coordinates": [116.37256372996957, 40.39798447055443], "category": "经济型", "name": &qu

  • 把JSON数据格式转换为Python的类对象方法详解(两种方法)

    JOSN字符串转换为自定义类实例对象 有时候我们有这种需求就是把一个JSON字符串转换为一个具体的Python类的实例,比如你接收到这样一个JSON字符串如下: {"Name": "Tom", "Sex": "Male", "BloodType": "A", "Hobbies": ["篮球", "足球"]} 我需要把这个转换为具

  • Python JSON格式数据的提取和保存的实现

    环境:python-3.6.5 JSON JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,它使得人们很容易的进行阅读和编写.同时也方便了机器进行解析和生成.适用于进行数据交互的场景,比如网站前台与后台之间的数据交互. Python中自带了json模块,直接import json即可使用 官方文档:https://docs.python.org/3/library/json.html Json在线解析网站:https://www.json.cn/# j

  • Python基于pandas实现json格式转换成dataframe的方法

    本文实例讲述了Python基于pandas实现json格式转换成dataframe的方法.分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- #!python3 import re import json from bs4 import BeautifulSoup import pandas as pd import requests import os from pandas.io.json import json_normalize class image_str

  • python判断字符串是否是json格式方法分享

    在实际工作中,有时候需要对判断字符串是否为合法的json格式 解决方法使用json.loads,这样更加符合'Pythonic'写法 代码示例: Python import json def is_json(myjson): try: json_object = json.loads(myjson) except ValueError, e: return False return True 运行代码编辑模式复制折叠 输出结果: Python print is_json("{}") #

  • Python中xml和json格式相互转换操作示例

    本文实例讲述了Python中xml和json格式相互转换操作.分享给大家供大家参考,具体如下: Python中xml和json格式是可以互转的,就像json格式转Python字典对象那样. xml格式和json格式互转用到的xmltodict库 安装xmltodict库 C:\Users\Administrator>pip3 install xmltodict Collecting xmltodict   Downloading xmltodict-0.11.0-py2.py3-none-any

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

    编写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.jso

  • python numpy格式化打印的实例

    1.问题描述 在使用numpy的时候,我们经常在debug的时候将numpy数组打印下来,但是有的时候数组里面都是小数,数组又比较大,打印下来的时候非常不适合观察.这里主要讲一下如何让numpy打印的结果更加简洁 2.问题解决 这里需要使用numpy的set_printoptions函数,对应numpy源码如下所示: def set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppr

  • python文字转语音实现过程解析

    这篇文章主要介绍了python文字转语音实现过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 使用百度接口 接口地址 https://ai.baidu.com/docs#/TTS-Online-Python-SDK/top 安装接口 pip install baidu-aip from aip import AipSpeech """ 你的 APPID AK SK """ APP_ID =

  • python打包成so文件过程解析

    这篇文章主要介绍了python打包成so文件过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 wget https://bootstrap.pypa.io/get-pip.py python get-pip.py pip install cython 编写setput.py文件: setup.py文件内容如下: from distutils.core import setup from distutils.extension import

  • python使用rsa非对称加密过程解析

    这篇文章主要介绍了python使用rsa非对称加密过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.安装rsa 支持python 2.7 或者 python 3.5 以上版本 使用豆瓣pypi源来安装rsa pip install -i https://pypi.douban.com/simple rsa 2.加密解密 2.1.生成公私钥对 import rsa # 1.接收者(A)生成512位公私钥对 # a. lemon_pub为

  • Python测试线程应用程序过程解析

    这篇文章主要介绍了Python测试线程应用程序过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在本章中,我们将学习线程应用程序的测试.我们还将了解测试的重要性. 为什么要测试? 在我们深入讨论测试的重要性之前,我们需要知道测试的内容.一般来说,测试是一种了解某些东西是如何运作的技术.另一方面,特别是如果我们谈论计算机程序或软件,那么测试就是访问软件程序功能的技术. 在本节中,我们将讨论软件测试的重要性.在软件开发中,必须在向客户端发布软

  • python全局变量引用与修改过程解析

    这篇文章主要介绍了python全局变量引用与修改过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一.引用 使用到的全局变量只是作为引用,不在函数中修改它的值的话,不需要加global关键字.如: #! /usr/bin/python a = 1 b = [2, 3] def func(): if a == 1: print("a: %d" %a) for i in range(4): if i in b: print(&quo

  • Python namedtuple命名元组实现过程解析

    这篇文章主要介绍了Python namedtuple命名元组实现过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 命名元组(namedtuple)是一种带有属性的元组,它们是组合只读数据的很好的方式. 相比一般的元组,构造命名元组需要先导入namedtuple,因为它不在默认的命名空间里.然后通过名字和属性来定义一个命名元组.这会返回一个像类一样的对象,可以进行多次实例化. 命名元组可以被打包.解包以及做所有可以对普通元组做的事,并且还可

  • python自动化unittest yaml使用过程解析

    这篇文章主要介绍了python自动化unittest yaml使用过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在编写unittest自动化用例时,一个请求需要编写多条用例,而涉及的参数基本相同,这时候就会用到配置文件,可以把参数配置项统一管理,避免重复代码,也方便后期维护 此处用到的是yaml,首先需要安装yaml库,pip install yaml 安装成功后,脚本导入语句,import yaml,具体语法可参照如上入门教程 举例

  • python json 递归打印所有json子节点信息的例子

    我就废话不多说了,直接上代码吧 def json_txt(self, dic_json): #self.debug_print("json_txt") if isinstance(dic_json, dict): # 判断是否是字典类型isinstance 返回True false for key in dic_json: #dic_json = json.loads(s) s = dic_json[key] #self.debug_print(str(len(s)) + "

随机推荐