Files
stock/scripts/iafd/merge/json2csv.py
2025-03-02 15:27:53 +08:00

72 lines
2.6 KiB
Python

import json
import csv
# 读取 detail_birth.json 文件
def read_json(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
print(f"文件 {file_path} 未找到.")
return []
except json.JSONDecodeError:
print(f"文件 {file_path} 解析错误.")
return []
# 写入 CSV 文件
def write_to_csv(data, output_file):
with open(output_file, 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=[
'person', 'href', 'performer_aka', 'birthday', 'astrology', 'birthplace', 'gender',
'years_active', 'ethnicity', 'nationality', 'hair_colors', 'eye_color', 'height',
'weight', 'measurements', 'tattoos', 'piercings'
])
writer.writeheader()
for entry in data:
# 确保 performer_aka 始终为列表类型
performer_aka = entry.get('performer_aka', [])
# 如果是 None 或非列表类型,转换为一个空列表
if performer_aka is None:
performer_aka = []
elif not isinstance(performer_aka, list):
performer_aka = [performer_aka]
# 写入每一行
writer.writerow({
'person': entry.get('person', ''),
'href': entry.get('href', ''),
'performer_aka': performer_aka,
'birthday': entry.get('birthday', ''),
'astrology': entry.get('astrology', ''),
'birthplace': entry.get('birthplace', ''),
'gender': entry.get('gender', ''),
'years_active': entry.get('years_active', ''),
'ethnicity': entry.get('ethnicity', ''),
'nationality': entry.get('nationality', ''),
'hair_colors': entry.get('hair_colors', ''),
'eye_color': entry.get('eye_color', ''),
'height': entry.get('height', ''),
'weight': entry.get('weight', ''),
'measurements': entry.get('measurements', ''),
'tattoos': entry.get('tattoos', ''),
'piercings': entry.get('piercings', '')
})
# 主函数,执行转化操作
def main():
# 输入的 JSON 文件路径
input_json_file = 'detail_birth.json'
# 输出的 CSV 文件路径
output_csv_file = 'detail_birth.csv'
# 读取 JSON 文件
data = read_json(input_json_file)
# 将数据写入 CSV 文件
write_to_csv(data, output_csv_file)
print(f"数据已保存到 {output_csv_file}")
if __name__ == "__main__":
main()