Python json中一直搞不清的load、loads、dump、dumps、eval

做接口测试的时候,有时候需要对字符串、json串进行一些转换,可是总是得花费一些时间,本质来说还是有可能是这几个方法的使用没有弄清楚。

@TOC

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)

在这里插入图片描述

1 声望
0 粉丝
0 条评论
推荐阅读
WindowsGUI自动化测试框架搭建之需求整理、详细设计和框架设计
1 需求整理1.1 实现目的基于CS架构,模拟用户(鼠标、键盘)操作,达到快速、重复执行测试用例;便于回归测试,快速覆盖主线用例或功能;线上或线下巡检测试,结合持续集成,及时发现运行环境存在的问题;提升个...

虫无涯阅读 397

又一款眼前一亮的Linux终端工具!
今天给大家介绍一款最近发现的功能十分强大,颜值非常高的一款终端工具。这个神器我是在其他公众号文章上看到的,但他们都没把它的强大之处介绍明白,所以我自己体验一波后,再向大家分享自己的体验。

良许6阅读 1.9k

FastAPI性能碾压Flask?
不止一次的听过,FastAPI性能碾压Flask,直追Golang,不过一直没有测试过,今天闲着没事测试一下看看结果。不知道是哪里出了问题,结果大跌眼镜。

二毛erma02阅读 10.3k评论 3

封面图
Linux终端居然也可以做文件浏览器?
大家好,我是良许。在抖音上做直播已经整整 5 个月了,我很自豪我一路坚持到了现在【笑脸】最近我在做直播的时候,也开始学习鱼皮大佬,直播写代码。当然我不懂 Java 后端,因此就写写自己擅长的 Shell 脚本。但...

良许1阅读 2.1k

Python之如何优雅的重试
为了避免偶尔的网络连接失败,需要加上重试机制,那么最简单的形式就是在对应的代码片段加一个循环,循环体里使用异常捕获,连接成功时退出循环,否则就重复执行相关逻辑,此时修改之后的函数f如下

Harpsichord12073阅读 7.4k

基于 EKS Fargate 搭建微服务性能分析系统
近期 Amazon Fargate 在中国区正式落地,因 Fargate 使用 Serverless 架构,更加适合对性能要求不敏感的服务使用,Pyroscope 是一款基于 Golang 开发的应用程序性能分析工具,Pyroscope 的服务端为无状态服务且性...

亚马逊云开发者阅读 7.8k

ChatGPT的开源平替,终于来了!
最近这段时间,一个号称全球最大ChatGPT开源平替项目Open Assistant引起了大家的注意。这不最近还登上了GitHub的Trending热榜。[链接]根据官方的介绍,Open Assistant也是一个对话式的大型语言模型项目,可以理解...

CodeSheep2阅读 1.1k

封面图
1 声望
0 粉丝
宣传栏