首页 > 编程语言 >如何在Python中使用JSON模块

如何在Python中使用JSON模块

时间:2023-06-06 12:55:40浏览次数:44  
标签:horoscope Python 数据 json JSON 模块 data

JSON(JavaScript Object Notation)是一种流行的轻量级数据交换标准。它表示由键值对组成的数据结构,非常简单易懂。

JSON 已成为在线服务之间数据交换的行业标准。它广泛用于现代编程语言,包括 Python。

JSON 数据经常表示为嵌套字典、列表和标量值,例如文本、数字、布尔值和空值。之所以命名为 JSON,是因为它非常模仿 JavaScript 对象中使用的语法。

在本教程中,您将探索 Python 中的 JSON 模块并学习如何有效地处理 JSON 数据。

(更多优质教程:java567.com,搜索"python")

Python 的内置 JSON 模块

JSON 在 Python 编程中扮演着重要的角色,因为它允许高效的数据序列化和反序列化。它使 Python 程序能够毫不费力地与 Web 服务通信、交换数据和存储结构化信息。

开发人员可以使用 JSON 将他们的 Python 程序与各种使用 JSON 进行数据表示的 API、数据库和外部系统无缝链接。

如果您希望了解如何使用 Python 与 Web 服务交互,请查看我关于请求模块的教程。

Python 中的内置 JSON 模块提供了一组功能强大的方法和类,使处理 JSON 数据变得简单。开发人员可以使用它将 Python 对象编码为 JSON 字符串,并将 JSON 字符串解码回 Python 对象。

如何在文件中存储 JSON 数据

在 Python 中处理 JSON 数据时,您通常需要保存数据或与他人共享。将 JSON 数据存储在文件中可以实现快速检索和数据持久化。

在本节中,您将学习如何使用 Python 的json.dump()函数将 JSON 数据保存到文件中。此过程涉及序列化 JSON 数据并将其保存到文件中,您随后可以根据需要读取和使用该文件。

函数json.dump()_

Python 中的函数json.dump()允许您将 JSON 数据直接存储到文件中。该函数有两个参数:要序列化的数据和将写入数据的文件对象。

要将 JSON 数据写入文件,您需要执行几个步骤。首先,您需要以写入模式打开一个文件,指定文件路径。然后,您可以使用json.dump()函数序列化数据并将其写入文件。最后,您需要关闭文件以确保所有数据都已正确保存。

让我们以星座 API 响应为例,学习如何将数据存储在文件中。

假设您向以下 URL 发出了 GET 请求:https://horoscope-app-api.vercel.app/api/v1/get-horoscope/daily?sign=capricorn&day=today,它提供摩羯座的每日星座运势符号。

 import requests
 import json
 ​
 # Make the GET request to the horoscope API
 response = requests.get("https://horoscope-app-api.vercel.app/api/v1/get-horoscope/daily?sign=capricorn&day=today")
 data = response.json()  # Convert the response to JSON
 ​
 # Store the JSON data in a file
 with open("horoscope_data.json", "w") as file:
     json.dump(data, file)
 ​
 print("Data stored successfully!")

在上面的代码中,您使用该库向Horoscope APIrequests发出 GET 请求。然后,您可以使用该方法从响应中提取 JSON 数据。最后,您使用该语句打开一个名为 write mode 的文件,并将数据存储在该文件中。.json()horoscope_data.jsonwith``json.dump()

查看本教程,了解如何使用 Python 找出你的星座。

如果您打开该horoscope_data.json文件,您将看到类似于以下的内容:

 {
   "data": {
     "date": "Jun 3, 2023",
     "horoscope_data": "The forecast today is stormy. You may have sensed that there was some tension clouding the conversation at home. Resentments were left unsaid and subtle power games were played without resolution. Today, Capricorn, it all becomes too unbearable for you. Regardless of the risks involved, you will take measures to clear things up."
  },
   "status": 200,
   "success": true
 }

如何从 JSON 文件中检索数据

您经常需要从 JSON 文件中读取数据。例如,您可能需要从 JSON 文件中读取配置设置。Python 的 JSON 模块提供了该json.load()功能,允许您从文件中读取和反序列化 JSON 数据。

在本节中,您将学习如何使用该json.load()函数从文件中检索 JSON 数据并在您的 Python 程序中使用它。

函数json.load()_

该json.load()函数接受一个文件对象作为参数,并以 Python 对象的形式返回反序列化的 JSON 数据,例如字典、列表、字符串、数字、布尔值和空值。

要从文件中读取 JSON 数据,您需要以读取模式打开文件,使用函数提取数据json.load(),并将其存储在变量中以供进一步处理。确保正在读取的文件包含有效的 JSON 数据很重要——否则,它可能会引发异常。

让我们看看如何从先前创建的文件中检索数据horoscope_data.json:

 import json
 ​
 # Retrieve JSON data from the file
 with open("horoscope_data.json", "r") as file:
     data = json.load(file)
 ​
 # Access and process the retrieved JSON data
 date = data["data"]["date"]
 horoscope_data = data["data"]["horoscope_data"]
 ​
 # Print the retrieved data
 print(f"Horoscope for date {date}: {horoscope_data}")

在上面的代码中,您horoscope_data.json使用语句以读取模式打开文件with。然后使用该json.load()函数将文件中的 JSON 数据反序列化到数据变量中。最后,您访问 JSON 数据的特定字段(例如,“date”和“horoscope_data”)并根据需要处理它们。

如何格式化 JSON 输出

当您从 JSON 文件中读取数据并打印时,输出显示为单行,这可能不像 JSON 的结构化格式。

 import json
 ​
 # Retrieve JSON data from the file
 with open("horoscope_data.json", "r") as file:
     data = json.load(file)
 ​
 print(data)

输出:

 {'data': {'date': 'Jun 3, 2023', 'horoscope_data': 'The forecast today is stormy. You may have sensed that there was some tension clouding the conversation at home. Resentments were left unsaid and subtle power games were played without resolution. Today, Capricorn, it all becomes too unbearable for you. Regardless of the risks involved, you will take measures to clear things up.'}, 'status': 200, 'success': True}

函数json.dumps()_

JSON 模块为您提供了json.dumps()将 Python 对象序列化为 JSON 格式字符串的功能。它提供了各种自定义选项,包括格式化输出以使其更易于阅读。

该json.dumps()函数提供了几个选项来自定义输出。最常用的是indent允许您指定用于缩进的空格数。

 import json
 ​
 # Retrieve JSON data from the file
 with open("horoscope_data.json", "r") as file:
     data = json.load(file)
 ​
 # Format the data
 formatted_data = json.dumps(data, indent=2)
 ​
 print(formatted_data)

输出:

 {
   "data": {
     "date": "Jun 3, 2023",
     "horoscope_data": "The forecast today is stormy. You may have sensed that there was some tension clouding the conversation at home. Resentments were left unsaid and subtle power games were played without resolution. Today, Capricorn, it all becomes too unbearable for you. Regardless of the risks involved, you will take measures to clear things up."
  },
   "status": 200,
   "success": true
 }

如您所见,JSON 数据现在采用适当的缩进格式,增强了其可读性。此技术可应用于任何 JSON 数据,使您能够以更有条理和更具视觉吸引力的方式呈现 JSON 输出。

命令json.tool行工具

Python 的 JSON 模块提供了一个方便的命令行工具,json.tool它允许您直接从命令行格式化和美化 JSON 数据。它是一种有用的实用程序,可以以更具可读性和组织性的格式快速可视化 JSON 数据的结构和内容。

要使用json.tool,您可以在命令行界面中执行以下命令:

 python -m json.tool <input_file> <output_file>

在哪里:

  • python -m json.tool``json.tool使用 Python 解释器调用模块。

  • <input_file>表示要格式化的 JSON 文件的路径。

  • <output_file>是一个可选参数,用于指定要将格式化的 JSON 输出保存到的文件。如果未提供,格式化输出将显示在控制台上。

假设您有一个horoscope_data.json包含以下内容的文件:

 {
   "data": {
     "date": "Jun 3, 2023",
     "horoscope_data": "The forecast today is stormy. You may have sensed that there was some tension clouding the conversation at home. Resentments were left unsaid and subtle power games were played without resolution. Today, Capricorn, it all becomes too unbearable for you. Regardless of the risks involved, you will take measures to clear things up."
  },
   "status": 200,
   "success": true
 }

请注意,上面的 JSON 文件缩进了两个空格。

要使用 漂亮地打印此 JSON 文件json.tool,您可以执行以下命令:

 python -m json.tool horoscope_data.json

输出将是:

 {
     "data": {
         "date": "Jun 3, 2023",
         "horoscope_data": "The forecast today is stormy. You may have sensed that there was some tension clouding the conversation at home. Resentments were left unsaid and subtle power games were played without resolution. Today, Capricorn, it all becomes too unbearable for you. Regardless of the risks involved, you will take measures to clear things up."
    },
     "status": 200,
     "success": true
 }

正如您在示例中看到的,json.tool使用输入文件路径执行模块会格式化 JSON 数据并在控制台上显示格式化的输出。

您还可以通过将输出文件名指定为第二个参数来将格式化输出重定向到输出文件:

 python -m json.tool horoscope_data.json formatted_data.json

此命令格式化 JSON 数据horoscope_data.json并将格式化的输出保存到formatted_data.json.

JSON 编码自定义对象

Python 中的 JSON 模块允许您使用 JSON 编码器和解码器类对自定义对象进行编码和解码。您可以使用这些类为您的对象定义自定义序列化和反序列化逻辑。

JSONEncoder类允许您自定义编码过程。要定义您的自定义对象应如何编码为 JSON 格式,您可以扩展JSONEncoder并更改其default方法。

下面是一个示例,说明如何扩展类JSONEncoder并为自定义对象自定义编码过程:

 import json
 ​
 ​
 class Person:
     def __init__(self, name, age):
         self.name = name
         self.age = age
 ​
 ​
 class PersonEncoder(json.JSONEncoder):
     def default(self, obj):
         if isinstance(obj, Person):
             return {"name": obj.name, "age": obj.age}
         return super().default(obj)
 ​
 ​
 # Create a custom object
 person = Person("Ashutosh Krishna", 23)
 ​
 # Encode the custom object using the custom encoder
 json_str = json.dumps(person, cls=PersonEncoder)
 ​
 # Print the encoded JSON string
 print(json_str)

Person在此示例中,您使用name和属性定义自定义类age。然后创建一个JSONEncodercalled的子类PersonEncoder并覆盖它的default方法。在该default方法中,您检查被编码的对象是否是Person. name如果是,则通过返回包含和属性的字典来提供对象的 JSON 可序列化表示age。如果对象不是类型Person,则调用default超类的方法来处理其他类型。

通过使用参数json.dumps并将其指定cls为自定义编码器类PersonEncoder,您可以将person对象编码为 JSON 字符串。输出将是:

 {"name": "Ashutosh Krishna", "age": 23}

同样,您可以在 JSON 解码器类中指定自定义解码逻辑JSONDecoder。要定义应如何将 JSON 数据解码为您的自定义对象,请扩展JSONDecoder并重写其object_hook函数。

如何从 Python 字典创建 JSON

您可以使用JSON 模块提供的函数从Python 字典json.dumps()创建 JSON 。此函数采用 Python 对象(通常是字典)并将其转换为 JSON 字符串表示形式。

 import json
 ​
 # Python dictionary
 data = {
     "name": "Ashutosh Krishna",
     "age": 23,
     "email": "[email protected]"
 }
 ​
 # Convert dictionary to JSON string
 json_str = json.dumps(data)
 ​
 # Print the JSON string
 print(json_str)

在此示例中,您有一个表示某些数据的 Python 字典data。通过调用json.dumps(data),您可以将字典转换为 JSON 字符串。输出将是:

 {"name": "Ashutosh Krishna", "age": 23, "email": "[email protected]"}

如何从 JSON 创建 Python 字典

要从 JSON 数据创建 Python 字典,可以使用json.loads()JSON 模块提供的函数。此函数采用 JSON 字符串并将其转换为相应的 Python 对象,通常是字典。

 import json
 ​
 # JSON string
 json_str = '{"name": "Ashutosh Krishna", "age": 23, "email": "[email protected]"}'
 ​
 # Convert JSON string to Python dictionary
 data = json.loads(json_str)
 ​
 # Access the dictionary values
 print(data["name"])
 print(data["age"])
 print(data["email"])

在此示例中,您有一个json_str表示某些数据的 JSON 字符串。通过调用json.loads(json_str),您可以将 JSON 字符串转换为 Python 字典。然后,您可以使用相应的键访问字典中的值。

输出将是:

 Ashutosh Krishna
 23
 [email protected]

包起来

了解 Python JSON 模块对于处理 JSON 数据是必要的,因为它广泛用于各种应用程序中的数据交换和存储。

如果您了解如何使用 JSON 模块,您可以高效地处理 JSON 数据、与 API 交互以及处理配置文件。

(更多优质教程:java567.com,搜索"python")

标签:horoscope,Python,数据,json,JSON,模块,data
From: https://www.cnblogs.com/web-666/p/17460250.html

相关文章

  • python离线下载安装包
    1.背景内网服务器不能直接连接外网,但是需要Python的mysql-connector-2.1.7包2.步骤#下载相关tar包https://pypi.doubanio.com/simple/mysql-connector/mysql-connector-2.1.7.tar.gz#上传到服务器后,解压tar-zxvfmysql-connector-2.1.7.tar.gz#进入解压目录,安装cdm......
  • python redis 链接集群 阿里云集群
    前言集群redis不支持选dbcluster方法里没有支持选中db的选项,javapy都不行#pipinstallredis==3.5.3#pipinstallredis-py-cluster==2.1.3#亲测,我是使用的这两个版本进行处理的fromredisclusterimportRedisClusternodes=[{"host":"dsfwwqfggy65aadfggi.redis.r......
  • 28) 跳过去 (只装父pom |不测试|构建特定模块)
    只装父pom跳过子命令行mvn-Ninstall-N,--non-recursive          Donotrecurseintosub-projectsusage:mvn[options][<goal(s)>][<phase(s)>]eclipse 跳过测试mvninstall-DskipTests http://maven.apache.org/surefire/maven-su......
  • IKCM10H60GA-ASEMI代理英飞凌功率模块IKCM10H60GA
    编辑:llIKCM10H60GA-ASEMI代理英飞凌功率模块IKCM10H60GA型号:IKCM10H60GA品牌:ASEMI封装:DIP-24正向电流:0.8A反向电压:600V引脚数量:3芯片个数:1芯片尺寸:漏电流:>10ua恢复时间: 浪涌电流:30A包装方式:盘装封装尺寸:如图特性:单向可控硅工作结温:-40℃~125℃......
  • 单片机+WiFi模块和主流物联网平台实现MQTT协议通信视频教程
    单片机+WiFi模块和主流物联网平台实现MQTT协议通信视频教程1、单片机+WiFi模块和阿里云物联网平台实现MQTT协议通信视频教程单片机+WiFi模块和阿里云物联网平台实现MQTT协议通信,阿里云物联网平台可以对单片机数字量输出、保持寄存器进行设置操作,单片机可以实时上报数字量输入、数......
  • python中同时指定多个分隔符将字符串拆分为列表
     001、>>>str1="ab_cdef_ghij_kl"##测试字符串>>>str1.split("")##一句空格进行拆分['ab_cd','ef_gh','ij_kl']>>>importre>>>re.split("......
  • Centos7 离线编译安装python3
    一,安装依赖yum-yinstallzlib-develbzip2-developenssl-develncurses-develreadline-develtk-develgccmake安装libffi-devel依赖yuminstalllibffi-devel-y注意:如果不安装这个包,python3可以装成功,但是后面装flask、uwsgi等依赖python3中有个内置模块叫ctype......
  • ARM架构---Python环境部署
    ARM架构---Python环境部署编译方式百度下即可,在ARM服务器编译出来就可以用1、上传python37.tar.gz文件到服务器py环境是在ARM架构上编译好的,可以直接拿编译产物去运行#例如上传到/data/software/目录cd/data/software/#解压tar-xfpython37.tar.gz#做软链接......
  • 万能的Python爬虫模板来了
    Python是一种非常适合用于编写网络爬虫的编程语言。以下是一些Python爬虫的基本步骤:1、导入所需的库:通常需要使用requests、BeautifulSoup、re等库来进行网络请求、解析HTML页面和正则表达式匹配等操作。2、发送网络请求:使用requests库发送HTTP请求,获取目标网页的HTML源代码。3、解......
  • OverTheWire攻关过程-Bandit模块33
    我们打开lv32-lv33,查看信息机器翻译在所有这些git的东西之后,是时候再次逃脱了。祝你好运!您可能需要解决此级别的命令嘘,伙计看来是需要sh命令先了解下sh命令我们登陆服务器查看信息已进入就是shell尝试了几个,发现不行输入$0可以得到正常的shellcat/etc/bandit_pass/bandit33得到密......