前言
在学习用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