首页 > 解决方案 > 为灯具转换 csv

问题描述

我无法使用CSV格式转换测试数据,csv2json.py以便我可以在应该具有 pk、模型和字段格式的夹具中使用相同的数据。

[
    {
        "pk": 1, 
        "model": "wkw2.Lawyer", 
        "fields": {
            "school": "The George Washington University Law School", 
            "last": "Babbas", 
            "firm_url": "http://www.graychase.com/babbas", 
            "year_graduated": "2005", 
            "firm_name": "Gray & Chase", 
            "first": "Amr A"
        }
    }
]

标签: django

解决方案


这是曾经帮助我将 CSV 转换为 JSON 的代码。如果您还需要其他东西,请告诉我:

import csv
import json

csvfile = open('file.csv', 'r')
jsonfile = open('file.json', 'w')

fieldnames = ("FirstName","LastName","IDNumber","Message")
reader = csv.DictReader( csvfile, fieldnames)
for row in reader:
    json.dump(row, jsonfile)
    jsonfile.write('\n')

推荐阅读