做接口測試的時候,有時候需要對字符串、json串進行一些轉換,可是總是得花費一些時間,本質來說還是有可能是這幾個方法的使用沒有弄清楚。
1、json.loads()
源碼:
def loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
"""Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance
containing a JSON document) to a Python object.
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
``object_pairs_hook`` is an optional function that will be called with the
result of any object literal decoded with an ordered list of pairs. The
return value of ``object_pairs_hook`` will be used instead of the ``dict``.
This feature can be used to implement custom decoders. If ``object_hook``
is also defined, the ``object_pairs_hook`` takes priority.
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
``parse_int``, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
``parse_constant``, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN.
This can be used to raise an exception if invalid JSON numbers
are encountered.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg; otherwise ``JSONDecoder`` is used.
The ``encoding`` argument is ignored and deprecated.
"""
作用:
將json格式的數據轉化爲字典類型
示例:
# -*- coding:utf-8 -*-
import json
json_str = '{"token":"dasgdhasdas", "status":0, "data":{"name":"admin", "password":123456}, "author":null}'
json_dict = json.loads(json_str)
print("====轉之前====")
print("type(json_str)", type(json_str))
print(json_str)
print("====轉之後====")
print("type(json_dict)", type(json_dict))
print(json_dict)
說明:
字符串裏有個null,轉了之後變成了None,已經變成Python格式的需求了,但是這個時候我們直接使用eval()進行轉的話,可能會報錯,提示‘null’沒有定義,所以如果有布爾類型的字符串轉字段時候使用loads()、沒有的話直接使用eval()也可以
# -*- coding:utf-8 -*-
import json
json_str = '{"token":"dasgdhasdas", "status":0, "data":{"name":"admin", "password":123456}, "author":null}'
json_dict = json.loads(json_str)
print("====轉之前====")
print("type(json_str)", type(json_str))
print(json_str)
print("====轉之後====")
print("type(json_dict)", type(json_dict))
print(json_dict)
json_eval = eval(json_str)
2、json.load()
源碼:
def load(fp, *, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
"""Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
a JSON document) to a Python object.
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
``object_pairs_hook`` is an optional function that will be called with the
result of any object literal decoded with an ordered list of pairs. The
return value of ``object_pairs_hook`` will be used instead of the ``dict``.
This feature can be used to implement custom decoders. If ``object_hook``
is also defined, the ``object_pairs_hook`` takes priority.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg; otherwise ``JSONDecoder`` is used.
"""
return loads(fp.read(),
cls=cls, object_hook=object_hook,
parse_float=parse_float, parse_int=parse_int,
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
作用:
從文件中讀取json類型的數據,並轉化爲字典類型
示例:
# -*- coding:utf-8 -*-
import json
# json_str = '{"token":"dasgdhasdas", "status":0, "data":{"name":"admin", "password":123456}, "author":null}'
# 文件中內容和json_str是一樣的
with open("file_str.txt", mode="r", encoding="utf-8") as file:
json_dict = json.load(file)
print("====轉之前====")
print("type(file", type(file))
print(file)
print("====轉之後====")
print("type(json_dict)", type(json_dict))
print(json_dict)
3、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.
"""
作用:
將Python中特定類型進行字符串化操作,即轉換爲json格式的數據
示例:
# -*- coding:utf-8 -*-
import json
json_dic = {"token":"dasgdhasdas", "status":0, "data":{"name":"隔壁老王", "password":123456}, "author":None}
json_str = json.dumps(json_dic)
json_str_str = str(json_dic)
print("====轉之前====")
print("type(json_dic)", type(json_dic))
print(json_dic)
print("====轉之後====")
print("type(json_str)", type(json_str))
print(json_str)
print("====使用str====")
print("type(json_str_str)", type(json_str_str))
print(json_str_str)
說明:
其實就類似於直接用str()進行強制轉換,但是dumps()轉了之後,有中文的被編碼了,那這個時候如果有中文的話,在轉換的時候,加ensure_ascii=False,如下:
# -*- coding:utf-8 -*-
import json
json_dic = {"token":"dasgdhasdas", "status":0, "data":{"name":"隔壁老王", "password":123456}, "author":None}
json_str = json.dumps(json_dic)
json_str_ensure_ascii = json.dumps(json_dic, ensure_ascii=False)
json_str_str = str(json_dic)
print("====轉之前====")
print("type(json_dic)", type(json_dic))
print(json_dic)
print("====轉之後====")
print("type(json_str)", type(json_str))
print("type(json_str_ensure_ascii)", type(json_str_ensure_ascii))
print(json_str_ensure_ascii)
print(json_str)
print("====使用str====")
print("type(json_str_str)", type(json_str_str))
print(json_str_str)
4、json.dump()
源碼:
在這裏插入代碼片def dump(obj, fp, *, 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`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
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 strings written to ``fp`` 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.
"""
作用:
將字典類型轉化爲json字符串格式,寫入到文件中
# -*- coding:utf-8 -*-
import json
json_dic = {"token":"dasgdhasdas", "status":0, "data":{"name":"隔壁老王", "password":123456}, "author":None}
with open("file.txt", mode="a", encoding="utf-8") as file:
json.dump(json_dic, file, ensure_ascii=False, indent=2)
5、eval()
源碼:
def eval(*args, **kwargs): # real signature unknown
"""
Evaluate the given source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
"""
pass
作用:
eval() 函數用來執行一個字符串表達式,並返回表達式的值。
示例:
# -*- coding:utf-8 -*-
import json
json_str = '{"token":"dasgdhasdas", "status":0, "data":{"name":"admin","password":123456}}'
json_eval = eval(json_str)
print("====轉之前====")
print("type(json_str)", type(json_str))
print(json_str)
print("====轉之後====")
print("type(json_eval )", type(json_eval ))
print(json_eval)