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

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

做接口测试的时候,有时候需要对字符串、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)

在这里插入图片描述

目录
相关文章
|
1月前
|
JSON 监控 安全
深入理解 Python 的 eval() 函数与空全局字典 {}
`eval()` 函数在 Python 中能将字符串解析为代码并执行,但伴随安全风险,尤其在处理不受信任的输入时。传递空全局字典 {} 可限制其访问内置对象,但仍存隐患。建议通过限制函数和变量、使用沙箱环境、避免复杂表达式、验证输入等提高安全性。更推荐使用 `ast.literal_eval()`、自定义解析器或 JSON 解析等替代方案,以确保代码安全性和可靠性。
45 2
|
3月前
|
JSON 数据格式 索引
Python中序列化/反序列化JSON格式的数据
【11月更文挑战第4天】本文介绍了 Python 中使用 `json` 模块进行序列化和反序列化的操作。序列化是指将 Python 对象(如字典、列表)转换为 JSON 字符串,主要使用 `json.dumps` 方法。示例包括基本的字典和列表序列化,以及自定义类的序列化。反序列化则是将 JSON 字符串转换回 Python 对象,使用 `json.loads` 方法。文中还提供了具体的代码示例,展示了如何处理不同类型的 Python 对象。
|
4月前
|
数据采集 JSON 数据处理
抓取和分析JSON数据:使用Python构建数据处理管道
在大数据时代,电商网站如亚马逊、京东等成为数据采集的重要来源。本文介绍如何使用Python结合代理IP、多线程等技术,高效、隐秘地抓取并处理电商网站的JSON数据。通过爬虫代理服务,模拟真实用户行为,提升抓取效率和稳定性。示例代码展示了如何抓取亚马逊商品信息并进行解析。
抓取和分析JSON数据:使用Python构建数据处理管道
|
4月前
|
JSON 数据格式 Python
Python编程:利用JSON模块编程验证用户
Python编程:利用JSON模块编程验证用户
40 1
|
6月前
|
Python
Python eval()函数的使用
Python eval()函数的使用
117 1
|
6月前
|
JSON 数据格式 Python
【2023最新】Matlab 保存JSON数据集文件,并用Python读取
本文介绍了如何使用MATLAB生成包含数据和标签的JSON格式数据集文件,并展示了用Python读取该JSON文件作为训练集的方法。
203 1
|
7月前
|
存储 JSON 数据格式
Python教程:json中load和loads的区别
【7月更文挑战第17天】在Python的`json`模块中, `load`与`loads`函数均用于JSON至Python对象的转换, 区别在于: - **`loads`**处理JSON格式的**字符串** 其中`data.json`文件内容为`{"name": "Bob", "age": 30}`。 简而言之, `loads`用于字符串, 而`load`用于文件对象。根据数据来源选择合适的方法。
163 5
|
7月前
|
Python
Python 中 eval 与 exec 的相同点和不同点
【7月更文挑战第17天】相同点: `eval` 和 `exec` 都能动态执行 Python 代码字符串。 不同点: 返回值 - `eval`: 计算表达式的值并返回结果。 - `exec`: 执行一系列语句,不返回任何值。 作用范围 - `eval`: 只能在当前作用域计算表达式。 - `exec`: 可以修改全局和局部变量。 输入的代码类型 - `eval`: 通常用于计算一个表达式。 - `exec`: 用于执行一系列语句。 总之,`eval` 更适合简单的表达式求值,而 `exec` 适用于执行更复杂的代码块。使用时需注意安全性,避免执行不可信的用户输入。
55 11
|
7月前
|
存储 JSON 测试技术
python中json和类对象的相互转化
针对python中类对象和json的相关转化问题, 本文介绍了4种方式,涉及了三个非常强大的python库jsonpickle、attrs和cattrs、pydantic,但是这些库的功能并未涉及太深。在工作中,遇到实际的问题时,可以根据这几种方法,灵活选取。 再回到结构化测试数据的构造,当需要对数据进行建模时,也就是赋予数据业务含义,pydantic应该是首选,目前(2024.7.1)来看,pydantic的生态非常活跃,各种基于pydantic的工具也非常多,建议尝试。
|
8月前
|
存储 JSON JavaScript
Python教程:一文了解Python中的json库
JSON(JavaScript Object Notation)是一种轻量级数据交换格式,易于人类阅读和编写,也易于计算机解析和生成。在Python中,JSON通常用于数据交换和存储,因为它与Python的字典和列表类型相似。
803 2

热门文章

最新文章