是否有任何选项可以使用 classes/objects 将 JSON 文件转换为 Python 中的 CSV?
Is there any option to convert JSON file to CSV in Python using classes/objects?
我想问一下是否有任何选项可以使用 classes/objects 将 JSON 文件中给出的数据转换为 CSV?它比简单地使用 pd.read_json 并将其转换为 DataFrame 然后再转换为 CSV 更有效吗?
我已经制作了一个 class 并成功地将 JSON 文件转换为对象列表,但是接下来呢?
PS。请记住,我是编程新手。
这是一个可能的解决方案。
假设我们的文件 data.json 包含以下数据
[
{"firstname": "John", "lastname": "Smith"},
{"firstname": "Ana", "lastname": "Smith"}
]
这是我们脚本的代码json_to_csv.py
import json
import csv
with open('data.json') as json_file:
data = json.load(json_file)
with open('example.csv', 'w', newline='') as csvfile:
fieldnames = ['firstname', 'lastname']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
这将生成包含 header 行 firstname,lastname
的 CSV 文件
example.csv
firstname,lastname
John,Smith
Ana,Smith
我想问一下是否有任何选项可以使用 classes/objects 将 JSON 文件中给出的数据转换为 CSV?它比简单地使用 pd.read_json 并将其转换为 DataFrame 然后再转换为 CSV 更有效吗?
我已经制作了一个 class 并成功地将 JSON 文件转换为对象列表,但是接下来呢?
PS。请记住,我是编程新手。
这是一个可能的解决方案。
假设我们的文件 data.json 包含以下数据
[
{"firstname": "John", "lastname": "Smith"},
{"firstname": "Ana", "lastname": "Smith"}
]
这是我们脚本的代码json_to_csv.py
import json
import csv
with open('data.json') as json_file:
data = json.load(json_file)
with open('example.csv', 'w', newline='') as csvfile:
fieldnames = ['firstname', 'lastname']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
这将生成包含 header 行 firstname,lastname
的 CSV 文件example.csv
firstname,lastname
John,Smith
Ana,Smith