MST

星途 面试题库

面试题:Python中常见数据存储格式转换之JSON与CSV

在Python中,如何将一个包含字典的列表(例如[{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}])转换为JSON格式的字符串,并写入文件?同时,如何将这个JSON数据读取出来,再转换为CSV格式并保存到另一个文件?
37.3万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
  1. 将包含字典的列表转换为JSON格式字符串并写入文件
import json

data = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]

# 转换为JSON格式字符串
json_data = json.dumps(data, indent=4)

# 写入文件
with open('data.json', 'w') as file:
    file.write(json_data)
  1. 从JSON文件读取数据并转换为CSV格式保存到另一个文件
import json
import csv

# 从JSON文件读取数据
with open('data.json', 'r') as file:
    json_data = json.load(file)

# 准备CSV数据
csv_data = []
headers = list(json_data[0].keys())
for item in json_data:
    csv_data.append(list(item.values()))

# 写入CSV文件
with open('data.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(headers)
    writer.writerows(csv_data)