在这篇文章中,我们将使用一个简单的Python脚本把CSV转换成JSON。我们将学习如何使用Python的JSON(JavaScript Object Notation)库,并将尝试理解这种转换背后的逻辑。
为什么要将CSV转换为JSON?
JSON是一种基于JavaScript对象语法的标准文本格式,用于表示结构化数据。它通常用于在网络应用程序中传输数据,因此每当需要从服务器向客户端发送一些数据时,首先将数据转换为JSON,然后发送到客户端,这样就可以在网页上显示,反之亦然。
将CSV转换为JSON所涉及的步骤
我们将以不同的小步骤来处理他的问题,这样我们就能彻底和容易地理解这个问题。
第1步: 输入CSV文件和JSON文件的路径
这可以在输入函数的帮助下实现。Input函数默认以字符串的形式输入,这正是我们需要的。Input函数也可以用来在要求输入时显示一些字符串。
第2步: 使用文件处理程序打开CSV文件
可以很容易地启动一个文件处理程序,有很多方法可以做到这一点,但我们将坚持使用最安全的方法,即我们将使用。
with open(csv_file_path, encoding = 'utf-8') as csv_file_handler:
这将以阅读模式打开文件,一旦我们离开这个块,它将自动关闭这个文件。在使用后关闭一个文件是非常重要的,以防止文件损坏或任何数据丢失的机会。
第3步: 使用JSON文件处理程序打开JSON文件
该文件将以写模式打开,因此代码变为:
with open(json_file_path, 'w', encoding = 'utf-8') as json_file_handler:
这里'+w'代表该文件是以写模式打开的,即它的数据可以被改变。
第四步: 使用JSON模块的功能将文件解析成JSON文件
这项任务可以通过使用以下代码轻松完成:
json_file_handler.write(json.dumps(data_dict, indent = 4))
你已经准备好了,现在你只需要运行这段代码,你的工作就完成了。
用Python将CSV转换成JSON的完整代码
import csv
import json
def csv_to_json(csv_file_path, json_file_path):
#create a dictionary
data_dict = {}
#Step 2
#open a csv file handler
with open(csv_file_path, encoding = 'utf-8') as csv_file_handler:
csv_reader = csv.DictReader(csv_file_handler)
#convert each row into a dictionary
#and add the converted data to the data_variable
for rows in csv_reader:
#assuming a column named 'No'
#to be the primary key
key = rows['Serial Number']
data_dict[key] = rows
#open a json file handler and use json.dumps
#method to dump the data
#Step 3
with open(json_file_path, 'w', encoding = 'utf-8') as json_file_handler:
#Step 4
json_file_handler.write(json.dumps(data_dict, indent = 4))
#driver code
#be careful while providing the path of the csv file
#provide the file path relative to your machine
#Step 1
csv_file_path = input('Enter the absolute path of the CSV file: ')
json_file_path = input('Enter the absolute path of the JSON file: ')
csv_to_json(csv_file_path, json_file_path)
运行该代码
输入Csv文件
运行脚本的命令
$ python3 "python script name without quotes"
在终端运行Python脚本
输出文件
生成的Json文件作为输出
总结
在这篇文章中,我们学习了如何实现一个能够创建/转换CSV到JSON的Python脚本。我们还了解了Python的 "json"和 "csv"模块以及它们的常用功能。