
本教程旨在指导用户如何使用python高效地将包含字典列表的json数据转换为结构化的csv文件。文章详细介绍了从理解复杂json数据结构到利用强大的pandas库进行数据处理和导出的完整流程,包括示例代码和最佳实践,确保数据能够准确、清晰地写入csv的每一行。
在数据处理和系统集成中,JSON(JavaScript Object Notation)是一种广泛使用的数据交换格式。然而,当需要将这些数据导入到电子表格或数据库中时,CSV(Comma Separated Values)文件格式更为常见。对于简单的扁平化JSON字典,将其键值对直接写入CSV行相对直接。但当JSON数据结构变得复杂,特别是当它包含一个字典列表时,传统的csv模块可能需要更多的手动迭代和处理。本教程将重点介绍如何优雅且高效地处理这种“字典列表”类型的JSON数据,并将其转换为规范的CSV文件。
在处理JSON数据时,首先要明确其结构。最初,您可能遇到的是一个扁平的JSON字典,例如:
{
"id": 1702,
"subnet": "10.111.0.0",
"mask": "21",
"description": "POD"
// ... 其他键值对
}对于这种结构,可以直接提取其键作为CSV的标题行,值作为数据行。
然而,更常见且复杂的情况是,JSON数据中包含一个键,其值是一个字典列表,例如来自API的响应通常会以这种形式返回多个记录:
立即学习“Python免费学习笔记(深入)”;
{
"data": [
{"id": 1713, "subnet": "10.111.0.0", "mask": "27", "description": "POD_Site"},
{"id": 1714, "subnet": "10.111.0.32", "mask": "27", "description": "POD_Site"},
{"id": 1715, "subnet": "10.111.0.64", "mask": "27", "description": "POD_Site"}
]
}在这种结构中,"data"是一个键,其对应的值是一个列表,而列表的每个元素又是一个独立的字典。我们的目标是让CSV文件中的每一行对应这个列表中的一个字典,字典的键成为CSV的列头,值成为对应列的数据。
Python的pandas库是处理和分析数据的强大工具,它提供了DataFrame这一核心数据结构,非常适合处理表格型数据。DataFrame能够直接从字典列表构建,并提供了便捷的方法将数据导出到CSV文件,极大地简化了这一过程。
首先,我们需要导入pandas库。如果您的环境中尚未安装,可以使用pip install pandas进行安装。
import pandas as pd import json # 如果数据是从JSON字符串加载而来
假设我们从API或其他来源获取了一个JSON字符串,并将其解析为Python字典。我们需要定位到包含字典列表的部分。
# 模拟从API获取的JSON响应
raw_json_data = """
{
"data": [
{"id": 1713, "subnet": "10.111.0.0", "mask": "27", "sectionId": 3, "description": "POD_Site", "linked_subnet": null, "firewallAddressObject": null, "vrfId": null, "masterSubnetId": 1702, "allowRequests": 0, "vlanId": null, "showName": 0, "device": null, "permissions": "{\"4\":\"3\"}", "pingSubnet": 0, "discoverSubnet": 0, "resolveDNS": 0, "DNSrecursive": 0, "DNSrecords": 0, "nameserverId": 0, "scanAgent": 0, "customer_id": null, "isFolder": 0, "isFull": 0, "isPool": 0, "tag": 2, "threshold": 0, "location": null, "editDate": null, "lastScan": null, "lastDiscovery": null},
{"id": 1714, "subnet": "10.111.0.32", "mask": "27", "sectionId": 3, "description": "POD_Site", "linked_subnet": null, "firewallAddressObject": null, "vrfId": null, "masterSubnetId": 1702, "allowRequests": 0, "vlanId": null, "showName": 0, "device": null, "permissions": "{\"4\":\"3\"}", "pingSubnet": 0, "discoverSubnet": 0, "resolveDNS": 0, "DNSrecursive": 0, "DNSrecords": 0, "nameserverId": 0, "scanAgent": 0, "customer_id": null, "isFolder": 0, "isFull": 0, "isPool": 0, "tag": 2, "threshold": 0, "location": null, "editDate": null, "lastScan": null, "lastDiscovery": null},
{"id": 1715, "subnet": "10.111.0.64", "mask": "27", "sectionId": 3, "description": "POD_Site", "linked_subnet": null, "firewallAddressObject": null, "vrfId": null, "masterSubnetId": 1702, "allowRequests": 0, "vlanId": null, "showName": 0, "device": null, "permissions": "{\"4\":\"3\"}", "pingSubnet": 0, "discoverSubnet": 0, "resolveDNS": 0, "DNSrecursive": 0, "DNSrecords": 0, "nameserverId": 0, "scanAgent": 0, "customer_id": null, "isFolder": 0, "isFull": 0, "isPool": 0, "tag": 2, "threshold": 0, "location": null, "editDate": null, "lastScan": null, "lastDiscovery": null}
]
}
"""
parsed_json = json.loads(raw_json_data)
# 提取包含字典列表的部分
data_for_csv = parsed_json["data"]在实际应用中,parsed_json可能直接是您的API响应对象,或者通过json.loads(res.content)等方式获得。关键是识别出那个包含列表的键(在本例中是"data"),并获取其值。
有了字典列表data_for_csv,创建DataFrame就非常简单了。pandas的DataFrame构造函数可以直接接受一个字典列表,并自动将每个字典转换为一行,字典的键作为列名。
df = pd.DataFrame(data_for_csv)
此时,df就是一个结构化的表格数据,包含了原始JSON数据中的所有信息。您可以通过print(df.head())查看前几行数据,确认其结构。
DataFrame对象提供了一个to_csv()方法,用于将数据导出到CSV文件。
df.to_csv('ipamsubnet.csv', index=False, encoding='utf-8')将以上步骤整合,形成一个完整的代码示例:
import pandas as pd
import json
# 模拟从API获取的JSON响应字符串
raw_json_data = """
{
"data": [
{"id": 1713, "subnet": "10.111.0.0", "mask": "27", "sectionId": 3, "description": "POD_Site", "linked_subnet": null, "firewallAddressObject": null, "vrfId": null, "masterSubnetId": 1702, "allowRequests": 0, "vlanId": null, "showName": 0, "device": null, "permissions": "{\"4\":\"3\"}", "pingSubnet": 0, "discoverSubnet": 0, "resolveDNS": 0, "DNSrecursive": 0, "DNSrecords": 0, "nameserverId": 0, "scanAgent": 0, "customer_id": null, "isFolder": 0, "isFull": 0, "isPool": 0, "tag": 2, "threshold": 0, "location": null, "editDate": null, "lastScan": null, "lastDiscovery": null},
{"id": 1714, "subnet": "10.111.0.32", "mask": "27", "sectionId": 3, "description": "POD_Site", "linked_subnet": null, "firewallAddressObject": null, "vrfId": null, "masterSubnetId": 1702, "allowRequests": 0, "vlanId": null, "showName": 0, "device": null, "permissions": "{\"4\":\"3\"}", "pingSubnet": 0, "discoverSubnet": 0, "resolveDNS": 0, "DNSrecursive": 0, "DNSrecords": 0, "nameserverId": 0, "scanAgent": 0, "customer_id": null, "isFolder": 0, "isFull": 0, "isPool": 0, "tag": 2, "threshold": 0, "location": null, "editDate": null, "lastScan": null, "lastDiscovery": null},
{"id": 1715, "subnet": "10.111.0.64", "mask": "27", "sectionId": 3, "description": "POD_Site", "linked_subnet": null, "firewallAddressObject": null, "vrfId": null, "masterSubnetId": 1702, "allowRequests": 0, "vlanId": null, "showName": 0, "device": null, "permissions": "{\"4\":\"3\"}", "pingSubnet": 0, "discoverSubnet": 0, "resolveDNS": 0, "DNSrecursive": 0, "DNSrecords": 0, "nameserverId": 0, "scanAgent": 0, "customer_id": null, "isFolder": 0, "isFull": 0, "isPool": 0, "tag": 2, "threshold": 0, "location": null, "editDate": null, "lastScan": null, "lastDiscovery": null}
]
}
"""
# 1. 解析JSON字符串为Python字典
parsed_json = json.loads(raw_json_data)
# 2. 提取包含字典列表的"data"键的值
data_to_process = parsed_json["data"]
# 3. 使用Pandas创建一个DataFrame
df = pd.DataFrame(data_to_process)
# 4. 将DataFrame写入CSV文件,不包含索引列,并指定UTF-8编码
output_filename = 'ipamsubnet.csv'
df.to_csv(output_filename, index=False, encoding='utf-8')
print(f"数据已成功写入到 {output_filename}")运行上述代码后,您将在脚本所在的目录下找到一个名为ipamsubnet.csv的文件。打开该文件,您会看到每个字典对应CSV中的一行,并且所有键都作为列标题。
通过本教程,我们学习了如何利用Python的pandas库高效地将包含字典列表的复杂JSON数据转换为结构化的CSV文件。pandas.DataFrame的强大功能和to_csv()方法的便捷性,使得这一常见的数据处理任务变得异常简单和直观。掌握这一技巧,将大大提升您在处理各种数据源时的效率和灵活性。
以上就是Python教程:高效将JSON中的字典列表写入CSV文件的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号