Python中的json模块的dump和dumps、load和loads的功能

2023-05-16

Python中的json模块的dump和dumps、load和loads的功能

JSON

首先简单介绍一下json格式文件。json是JavaScript Object Notation的缩写。顾名思义,json来源于js的对象的格式。现在json已经不在局限于某种语言,而是一种通用的,比xml更轻量级的数据交换形式。

json 的基本格式可以看做是嵌套的字典。通俗来讲,就是再字典中的某个元素的值还是一个字典。我们都熟悉Python的字典dict类型,如果我们定义

json_dict = {'a':{'c':{'e':404}, 'f':233}, 'b':{'d':1}}

可以看到,'a’的取值是一个字典,这个字典包括’c’和’f’两个key。其中,'c’的取值仍然是个字典,而f的取值则是一个数值。以此类推。。。这样一个字典具有清晰的结构关系。因此可以用来传输一个具有结构化的数据体。

下面,我们看看json官网上的介绍:

JSON具有以下这些形式:

对象(object) 是一个无序的“‘名称/值’对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’ 对”之间使用“,”(逗号)分隔。

数组(array) 是值(value)的有序集合。一个数组以“[”(左中括号)开始,“]”(右中括号)结束。值之间使用“,”(逗号)分隔。

在这里插入图片描述

值(value) 可以是双引号括起来的字符串(string)、数值(number)、truefalsenull、对象(object)或者数组(array)。这些结构可以嵌套。

在这里插入图片描述

字符串(string) 是由双引号包围的任意数量Unicode字符的集合,使用反斜线转义。一个字符(character)即一个单独的字符串(character string)。

JSON的字符串(string)与C或者Java的字符串非常相似。

在这里插入图片描述

数值(number) 也与C或者Java的数值非常相似。只是JSON的数值没有使用八进制与十六进制格式。

在这里插入图片描述

同时,可以在任意标记之间添加空白。

Python中的json模块

Python的json模块用于处理json格式的数据。主要有如下几个函数:

  • json.dump()

  • json.dumps()

  • json.load()

  • json.loads()

dump是将python的dict数据体做成json形式,而load则相反,从文件或string中加载数据,并解析成dict的形式。

简单来说,s可以理解为string,带有s的是将dict结构dump成str,或者从str中load一个dict,而没有s的则将dict以json形式存到文件,或者从文件读出json形式。

下面是官方文档的usage:

json.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)

可以看出,dump主要的参数是obj和fp,分别代表dict和要保存的文件的handler,如果需要打印出来缩进好看的话,可以设置indent。另外,separator是一个二元组(item_sep, key_sep),也就是元素之间的分隔符,和key-value之间的分隔符,默认的是逗号和冒号,并且如果没有indent,则逗号冒号后面都接一个空格,如果有indent,自然逗号后面就不需要空格了(因为有缩进)。这个分隔符可以自行指定。还有一个比较有用的是sort_keys,如果指定为True,则会按照key 进行排序。

json.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)

和上面一样,只不过不是保存到file里,而是转成一个string。

Serialize obj to a JSON formatted str using this conversion table. The arguments have the same meaning as in dump(). Note Keys in key/value pairs of JSON are always of the type str. When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, loads(dumps(x)) != x if x has non-string keys.

json.load(fp, *, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

load和loads同理。

Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table. object_hook is an optional function that will be called with the result of any object literal decoded (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. Changed in version 3.1: Added support for object_pairs_hook. 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. Changed in version 3.1: parse_constant doesn’t get called on ‘null’, ‘true’, ‘false’ anymore. To use a custom JSONDecoder subclass, specify it with the cls kwarg; otherwise JSONDecoder is used. Additional keyword arguments will be passed to the constructor of the class. If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised. Changed in version 3.6: All optional parameters are now keyword-only. Changed in version 3.6: fp can now be a binary file. The input encoding should be UTF-8, UTF-16 or UTF-32.

json.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 using this conversion table. The other arguments have the same meaning as in load(), except encoding which is ignored and deprecated. If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised. Changed in version 3.6: s can now be of type bytes or bytearray. The input encoding should be UTF-8, UTF-16 or UTF-32.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python中的json模块的dump和dumps、load和loads的功能 的相关文章

  • 在 Python 中使用 Selenium 处理“接受 Cookie”弹出窗口

    我一直在尝试用硒抓取这个房地产网站的一些信息 但是 当我访问该网站时 我需要接受 cookie 才能继续 这仅在机器人访问网站时发生 而不是在我手动执行时发生 当我尝试通过 xpath 或 id 查找相应的元素时 正如我在手动检查页面时找到
  • 为什么 .setGeometry() 不改变 QWidget 实例的大小?

    我想使用 QWidget 更改 QPushButton 的大小 setGeometry https doc qt io qtforpython 5 PySide2 QtWidgets QWidget html PySide2 QtWidge
  • 在 Numpy 中切片后确定结果数组的形状

    我很难理解在 numpy 中切片后如何确定结果数组的形状 例如 我使用以下简单代码 import numpy as np array np arange 27 reshape 3 3 3 slice1 array 1 2 1 slice2
  • 如何从 PyCharm 项目中获取我的“exe”[重复]

    这个问题在这里已经有答案了 通过 PyCharm 在 Python 上编写一些项目 我想从中获取一个exe文件 我尝试过 另存为 gt XXX exe 但是 当我尝试执行它时出现错误 此类操作系统不支持该文件 附注 我有win7 x64 它
  • 如何使用Python将WebP图像转换为Gif?

    我已经尝试过这个 from PIL import Image im Image open this webp im save that gif gif save all True 这给了我这个错误 类型错误 不支持的操作数类型 tuple
  • 优化 Keras 以使用所有可用的 CPU 资源

    好吧 我真的不知道我在说什么 所以请耐心听我说 我正在使用 Theano 后端运行 Keras 以在 MNIST 图像上运行基本的神经网络 目前只是一个教程 过去 我一直使用我的旧 HP 笔记本电脑 因为我有 Windows 和 Ubunt
  • Paramiko - 使用私钥连接 - 不是有效的 OPENSSH 私钥/公钥文件

    我正在尝试找到解决方案 但无法理解我做错了什么 在我的 Linux 服务器上 我运行了以下命令 ssh keygen t rsa 这产生了一个id rsa and id rsa pub file 然后我将它们复制到本地并尝试运行以下代码 s
  • PIL Image.size 返回相反的宽度/高度

    使用PIL确定图像的宽度和高度 在特定图像上 幸运的是只有这一个 但这很麻烦 从 image size 返回的宽度 高度是相反的 图片 http storage googleapis com cookila 533ebf752b9d1f7c
  • Pandas重置索引未生效[重复]

    这个问题在这里已经有答案了 我不确定我在哪里误入歧途 但我似乎无法重置数据帧上的索引 当我跑步时test head 我得到以下输出 正如您所看到的 数据帧是一个切片 因此索引超出范围 我想做的是重置该数据帧的索引 所以我跑test rese
  • 如果字段值在外部列表中,Django 会注释布尔值

    想象一下我有这个 Django 模型 class Letter models Model name models CharField max length 1 unique True 还有这个列表 vowels a e i o u 我想查询
  • 如何从 Dockerfile 安装 Python 3.7 和 Pip

    我正在尝试构建基于 Ubuntu 18 04 的自定义 Docker 映像 Ubuntu 预装了 Python 3 6 但我想 1 安装 Python 3 7 2 将其设置为默认 Python 版本 这样就可以使用python代替pytho
  • “char”/“character”类型的类型提示

    char 或 character 没有内置的原始类型 因此显然必须使用长度为 1 的字符串 但是为了暗示这一点并暗示它应该被视为一个字符 如何通过类型提示来实现这一点 grade chr A 一种方法可能是使用内置的 chr 函数来表示这一
  • 创建一个类似于 Tkinter 的表

    我希望创建类似于 Tkinter 中的表格的东西 但它不一定是这样的 例如 我想创建标题 Name1 Name2 Value 并在每个标题下面有几个空白行 然后 我希望稍后用我计算的值或名称的字符串值填充这些行 因此是标签 对于 Name2
  • 在可编辑的QSqlQueryModel中实现setEditStrategy

    这是后续这个问题 https stackoverflow com questions 49752388 editable qtableview of complex sql query 在那里 我们创建了 QSqlQueryModel 的可
  • Matplotlib Scatter - ValueError:RGBA 序列的长度应为 3 或 4

    我正在尝试为我的功能绘制图表 但不断收到此错误 ValueError RGBA sequence should have length 3 or 4 每当我只有 6 种形状时 代码就可以完美运行 但现在我将其增加到 10 种 它就不起作用了
  • 查找给定节点的最高权重边

    我在 NetworkX 中有一个有向图 边缘的权重从 0 到 1 表示它们发生的概率 网络连通性非常高 所以我想修剪每个节点的边缘 只保留最高概率的节点 我不确定如何迭代每个节点并仅保留最高权重in edges在图中 有没有一个networ
  • Python组合目录中的所有csv文件并按日期时间排序

    我有 2 年的每日数据分成每月文件 我想将所有这些数据合并到一个按日期和时间排序的文件中 我正在使用的代码组合了所有文件 但不按顺序 我正在使用的代码 import pandas as pd import glob os import cs
  • 为什么我们应该在 def __init__(self, n) -> None: 中使用 -> ?

    我们为什么要使用 gt in def init self n gt None 我读了以下摘录来自 PEP 484 https www python org dev peps pep 0484 the meaning of annotatio
  • 在 Python 模块中使用 InstaLoader

    我正在尝试使用 Instaloader 下载与主题标签相关的照片以进行图像分析 我在GitHub存储库中找到了一个全面的方法 如何在终端中执行它 但是 我需要将脚本集成到Python笔记本中 这是脚本 instaloader no vide
  • 来自 django 教程 was_published_recently.admin_order_field = 'pub_date'

    From Django 教程 https www jetbrains com help pycharm 2017 1 creating and running your first django project html d28041e21

随机推荐