我使用以下代码通过C#将csv转换为json:
var jsonWrtr = new StreamWriter(targetFile + ".json");
var csv = new List<string[]>(); // or, List<YourClass>
var lines = System.IO.File.ReadAllLines(targetFile + ".csv");
foreach (string line in lines) { csv.Add(line.Split(',')); }
string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(csv);
jsonWrtr.Write(json);
jsonWrtr.Close();
以下是输出内容的示例:
[["Type","Id","Name","Age","Org","DOB","FirstName","LastName","Flight"],["1","2","3","4","5","6","7","8","9"],["1","2","3","4","5","6","7","8","9"]]
我希望输出格式如下:
[{
"Type" : "1",
"Id" : "2",
"Name" : "3",
"Age" : "4",
"Org" : "5",
"Dob" : "6", ,
"FirstName" : "7",
"LastName" : "8",
"Flight" : "9",
}, {
"Type" : "1",
"Id" : "2",
"Name" : "3",
"Age" : "4",
"Org" : "5",
"Dob" : "6", ,
"FirstName" : "7",
"LastName" : "8",
"Flight" : "9",
}
]
任何想法为什么它不起作用?
答案 0 :(得分:6)
代码产生的输出是预期的输出。您必须将数据转换为所需的格式。以下是如何执行此操作的示例:
static void Main(string[] args)
{
var lines = @"A,B,C
1,2,3
4,5,6".Replace("\r", "").Split('\n');
var csv = lines.Select(l => l.Split(',')).ToList();
var headers = csv[0];
var dicts = csv.Skip(1).Select(row => Enumerable.Zip(headers, row, Tuple.Create).ToDictionary(p => p.Item1, p => p.Item2)).ToArray();
string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(dicts);
Console.WriteLine(json);
}