[转载] python对象转json字符串,及json字符串的格式化

参考链接: Python-Json 5 : python自定义class进行Json格式化

文章目录

 前言一、python对象转化成json字符串?1.引入库2.转化

  二、json字符串的格式化1.使用json.dumps(obj,indent=n)方法2.示例3.结果展示

  总结

 

 

 

前言 

在学习用requests库进行接口测试时遇到了一个问题----怎么将响应获取到的(json格式)内容以我们想要的格式输出呢? 

 

提示:本篇文章以python语言结合requests库实现 

一、python对象转化成json字符串? 

1.引入库 

import json

 

2.转化 

1.使用json.dumps(obj,indent=n)方法 

# obj为需要进行转化的pyhton对象

json.dumps(obj)

 

二、json字符串的格式化 

1.使用json.dumps(obj,indent=n)方法 

查看源码: 

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.

 

    """

 

这里我们主要关注indent参数,indent表示缩进,indent=2表示我们想要缩进的值为2(源码里面默认是无缩进的) 

2.示例 

代码如下(示例): 

import requests

import json

 

# 请求地址

url = "http://127.0.0.1:8000/api/departments/"

# 相应内容

response = requests.get(url)

# 返回响应的json编码内容

res = response.json()  # 注意:当确定返回内容为json格式时再使用response.json()方法

print(res)

print(type(res))  # 字典类型

# 对返回值进行格式化输出(使用json库实现)

# json.loads() # 将json字符串转化成pyhton对象

# 将python对象转化成json字符串,indent表缩进

result = json.dumps(res, indent=2,ensure_ascii=False)

print(result)

print(type(result))  # <class 'str'>

 

示例中,ensure_ascii=False表示非ascii字符编码不做转化; ensure_ascii默认值为True,设置为False是为了让响应内容中的中文以原中文形式输出(不做编码转换) 

3.结果展示 

{'count': 20, 'next': None, 'previous': None, 'results': [{'dep_id': 'T02', 'dep_name': 'Java_2学院', 'master_name': 'Java-Master', 'slogan': 'java'}, {'dep_id': 'T03', 'dep_name': 'C++/学院', 'master_name': 'C++-Master', 'slogan': 'ljx_put_test'}, {'dep_id': 'T04', 'dep_name': 'C++/学院', 'master_name': 'C++-Master', 'slogan': 'Here is Slogan'}, {'dep_id': 'T01', 'dep_name': 'Test学院', 'master_name': 'Test-Master', 'slogan': 'Here is Slogan'}, {'dep_id': '10', 'dep_name': '超神_10', 'master_name': '陆兴雷_10', 'slogan': '带头学习'}, {'dep_id': '11', 'dep_name': '超神_11', 'master_name': '陆兴雷_11', 'slogan': '带头学习'}, {'dep_id': '12', 'dep_name': '超神_12', 'master_name': '陆兴雷_12', 'slogan': '带头学习'}, {'dep_id': '13', 'dep_name': '超神_13', 'master_name': '陆兴雷_13', 'slogan': '带头学习'}, {'dep_id': '14', 'dep_name': '超神_14', 'master_name': '陆兴雷_14', 'slogan': '带头学习'}, {'dep_id': '15', 'dep_name': '超神_15', 'master_name': '陆兴雷_15', 'slogan': '带头学习'}, {'dep_id': '16', 'dep_name': '超神_16', 'master_name': '陆兴雷_16', 'slogan': '带头学习'}, {'dep_id': '17', 'dep_name': '超神_17', 'master_name': '陆兴雷_17', 'slogan': '带头学习'}, {'dep_id': '18', 'dep_name': '超神_18', 'master_name': '陆兴雷_18', 'slogan': '带头学习'}, {'dep_id': '19', 'dep_name': '超神_19', 'master_name': '陆兴雷_19', 'slogan': '带头学习'}, {'dep_id': '20', 'dep_name': '超神_20', 'master_name': '陆兴雷_20', 'slogan': '带头学习'}, {'dep_id': 'T05', 'dep_name': '班德尔学院', 'master_name': '李宏伟', 'slogan': 'XXXXXXXXXX'}, {'dep_id': 'T06', 'dep_name': '许愿', 'master_name': 'jerry', 'slogan': '33330'}, {'dep_id': 'T21', 'dep_name': 'Test学院', 'master_name': 'Test-Master', 'slogan': 'Here is test_ljx'}, {'dep_id': 'T22', 'dep_name': 'ljx学院', 'master_name': 'ljx-Master', 'slogan': 'test_ljx'}, {'dep_id': 'ljx_01', 'dep_name': '计信学院_1', 'master_name': 'master_1', 'slogan': 'test_ljx_1'}]}

<class 'dict'>

{

  "count": 20,

  "next": null,

  "previous": null,

  "results": [

    {

      "dep_id": "T02",

      "dep_name": "Java_2学院",

      "master_name": "Java-Master",

      "slogan": "java"

    },

    {

      "dep_id": "T03",

      "dep_name": "C++/学院",

      "master_name": "C++-Master",

      "slogan": "ljx_put_test"

    },

    {

      "dep_id": "T04",

      "dep_name": "C++/学院",

      "master_name": "C++-Master",

      "slogan": "Here is Slogan"

    },

    {

      "dep_id": "T01",

      "dep_name": "Test学院",

      "master_name": "Test-Master",

      "slogan": "Here is Slogan"

    },

    {

      "dep_id": "10",

      "dep_name": "超神_10",

      "master_name": "陆兴雷_10",

      "slogan": "带头学习"

    },

    {

      "dep_id": "11",

      "dep_name": "超神_11",

      "master_name": "陆兴雷_11",

      "slogan": "带头学习"

    },

    {

      "dep_id": "12",

      "dep_name": "超神_12",

      "master_name": "陆兴雷_12",

      "slogan": "带头学习"

    },

    {

      "dep_id": "13",

      "dep_name": "超神_13",

      "master_name": "陆兴雷_13",

      "slogan": "带头学习"

    },

    {

      "dep_id": "14",

      "dep_name": "超神_14",

      "master_name": "陆兴雷_14",

      "slogan": "带头学习"

    },

    {

      "dep_id": "15",

      "dep_name": "超神_15",

      "master_name": "陆兴雷_15",

      "slogan": "带头学习"

    },

    {

      "dep_id": "16",

      "dep_name": "超神_16",

      "master_name": "陆兴雷_16",

      "slogan": "带头学习"

    },

    {

      "dep_id": "17",

      "dep_name": "超神_17",

      "master_name": "陆兴雷_17",

      "slogan": "带头学习"

    },

    {

      "dep_id": "18",

      "dep_name": "超神_18",

      "master_name": "陆兴雷_18",

      "slogan": "带头学习"

    },

    {

      "dep_id": "19",

      "dep_name": "超神_19",

      "master_name": "陆兴雷_19",

      "slogan": "带头学习"

    },

    {

      "dep_id": "20",

      "dep_name": "超神_20",

      "master_name": "陆兴雷_20",

      "slogan": "带头学习"

    },

    {

      "dep_id": "T05",

      "dep_name": "班德尔学院",

      "master_name": "李宏伟",

      "slogan": "XXXXXXXXXX"

    },

    {

      "dep_id": "T06",

      "dep_name": "许愿",

      "master_name": "jerry",

      "slogan": "33330"

    },

    {

      "dep_id": "T21",

      "dep_name": "Test学院",

      "master_name": "Test-Master",

      "slogan": "Here is test_ljx"

    },

    {

      "dep_id": "T22",

      "dep_name": "ljx学院",

      "master_name": "ljx-Master",

      "slogan": "test_ljx"

    },

    {

      "dep_id": "ljx_01",

      "dep_name": "计信学院_1",

      "master_name": "master_1",

      "slogan": "test_ljx_1"

    }

  ]

}

<class 'str'>

 

进程已结束,退出代码 0

 

 

 

总结 

 以上就是今天的学习小结

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值