python如何读取json文件?使用JSON模块在Python中存储数据

2021年11月7日13:53:25 发表评论 2,137 次浏览

某些程序可能需要用户接受不同类型的数据。无论程序的目的是什么,你都需要像列表和字典这样的数据结构来存储它们。你将始终希望在用户关闭程序之前保存用户输入的数据。最简单的方法是python使用json模块存储数据

python如何读取json文件?在本教程中,我们将了解如何使用 JSON 模块在 Python 中存储数据。我们也将学习如何使用json.dump()json.dumps()方法,json.load()json.loads()方法,以及他们之间的分歧。最后,我们将看看如何在 Python 中将 JSON 序列化和反序列化为 Object。

先决条件

有一定的Python编程语言基础知识。

为什么使用 JSON 模块在 Python 中存储数据?

  1. 使开发人员能够将简单的数据结构转储到文件中并在需要时加载它们
  2. 可以使用 JSON 在 Python 程序之间共享数据
  3. JSON 格式与平台或语言无关。当你以 JSON 格式存储数据时,你也可以在其他编程语言中轻松使用它们
  4. 易于学习且采用便携式格式

python读取json文件示例:使用 json.dump()

要使用json.dump()函数先导入json模块。要导入json模块,请使用import json. 这json.dump()有助于将数据写入 JSON 文件。

句法:

json.dump(data, file)

json.dump()函数接受两个参数:

  1. 需要写入 JSON 文件的数据。
  2. 可用于保存数据的文件对象

python读取json文件的方法:让我们开发一个快速程序来将一组数字保存在 JSON 文件中。为了保存这组数字,我们将使用json.dump()函数:

import json

numbers = [10, 20, 30, 70, 191, 23]  #create a set of numbers
filename = 'numbers.json'          #use the file extension .json
with open(filename, 'w') as file_object:  #open the file in write mode
 json.dump(numbers, file_object)   # json.dump() function to stores the set of numbers in numbers.json file

在这个程序中,我们将一组数字存储在numbers.json. 扩展名.json显示该文件包含 JSON 格式的数据。

然后我们以'w'模式(写入模式)访问文件,以使数据能够写入 JSON 文件。最后,该json.dump()函数将这组数字存储在文件numbers.jsonfile 中。

这个程序没有终端输出,但是当我们打开文件时,numbers.json我们看到以下数据:

[10, 20, 30, 70, 191, 23]

python如何读取json文件?使用 json.dumps()

json.dumps()可用于转化Python对象成JSON字符串。

句法:

json.dumps(data)

json.dumps()函数接受一个参数,即要转换为 JSON 字符串的数据。

让我们看看下面的例子:

import json
data = {
    'Name' : 'Felix',
    'Occupation' : 'Doctor'
}
dict_1 = json.dumps(data) # converting dictionary to JSON
print(dict_1)   # {'Name' : 'Felix','Occupation' : 'Doctor'}

json.dumps() 和 json.dump() 的区别

  1. dump()方法需要两个参数(数据和文件),而该dumps()方法只需要一个参数(数据)
  2. dump()方法与文件操作相结合,与dumps()方法不同。

使用 json.load()

python使用json模块存储数据:我们使用该json.load函数读取 JSON 文件。

json.load()函数采用一个参数,即文件对象。

句法:

json.load(file_object)

假设我们有一个名为 的 JSON 文件student.json,其中包含 JSON 对象。

{
    "name": "Felix",   
    "Subjects": ["English", "Political Science"]  
}  

让我们编写一个代码来student.json使用该json.load函数读取存储在文件中的数据。

import json  
  
with open(r,'student.json') as file_object:  
  data = json.load(file_object)  
print(data)   # {"name": "Felix", "Subjects": ["English", "Political Science"]}

json.load()函数解析 JSON 文件并返回一个名为 的字典data

使用 json.loads()

我们使用该json.loads()方法解析一个 JSON 字符串并返回一个 Python 对象,例如字典。该json.loads()方法将文件内容作为字符串。

句法:

json.loads(json_string)

python读取json文件示例:

import json
  
# JSON string:
dict_1 = {
    "Name": "Felix Maina",
    "Contact Number": 0712345678,
    "Email": "fely@gmail.com",
    }
  
# parse dict_1:
y = json.loads(dict_1)
# the result is a Python dictionary:
print(y)   #{ "Name": "Felix Maina", "Contact Number": 0712345678,"Email": "fely@gmail.com", }

在这里,dict_1使用json.loads()返回名为 的字典的方法解析字符串y

注意:json.loads()和之间的主要区别json.load()json.loads()读取字符串而json.load()用于读取文件。

在 Python 中序列化 JSON 数据

序列化是将本机数据类型转换为 JSON 格式的过程。

python如何读取json文件?该JSON 模块将 Python 字典对象转换为 JSON 对象。的json.dump()json.dumps()方法用于序列化Python数据到JSON格式。

我们来看一个使用该json.dump()方法的例子:

import json
# Data to be written
details = {
        "name": "Felix Maina",
        "years": 21,
        "school": "Makerere"
}
# Serializing JSON and writing JSON file
with open("details.json", "w") as file_object:
    json.dump(details, file_object)  # {"name": "Felix Maina", "years": 21, "school": "Makerere"}

在这里,我们将 Python 字典转换为名为 .json 的 JSON 格式文件details.json

json.dumps()方法将 Python 对象转换为 JSON 字符串,如下所示:

import json
# Data to be written
details = {
        "name": "Felix Maina",
        "years": 21,
        "school": "Makerere"
}
# Serializing JSON
json_string = json.dumps( details )
print( json_string )  #{"name": "Felix Maina", "years": 21, "school": "Makerere"}

在 Python 中将 JSON 反序列化为对象

反序列化是将 JSON 数据转换为原生数据类型的过程。在这里,我们将 JSON 数据转换回 Python 中的字典。

python使用json模块存储数据:我们使用该json.loads()方法将 JSON 数据反序列化为 Python 对象。该json.load()方法还用于将 JSON 格式的文件反序列化为 Python 对象。

python读取json文件示例示例:使用loads()# 导入模块进行反序列化

# importing the module
import json
  
# creating the JSON data as a string
data = '{"Name" : "Felix", "status" : "married"}'
print("data before deserailizing")
print(data) #json string
   
# deserailizing the data
h = json.loads(data)
print("data after deserailizing")
print(h) #python dictionary

输出

data before deserailizing
{"Name" : "Felix", "status" : "married"}
data after deserailizing
{'status': 'married', 'Name': 'Felix'}

让我们创建一个文件并将其命名为cars.json. 该文件应包含以下数据:

 {
    "name": "Suzuki",
    "year": 2001,
    "model": "GDF10"
}

python读取json文件的方法:现在让我们使用load()函数反序列化这个文件:

import json
# opening the JSON file 
data = open('cars.json','r') 
print("Datatype before deserialization : ")
print(data) # prints the contents of the file
     
# deserailizing the data
h = json.load(data) 
print("Datatype after deserialization : ")
print(h)  # prints a python dictionary

结论

python如何读取json文件?在本文中,我们了解了以下内容:

  • 使用 JSON 模块在 Python 中存储数据的原因
  • 使用json.dump(),json.dumps()以及它们的区别
  • 使用json.load(),json.loads()以及它们的区别
  • 在 Python 中序列化和反序列化 JSON 数据
木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: