gpt4 book ai didi

c# - 使用 JavaScriptSerializer 将 csv 转换为 JSON

转载 作者:太空宇宙 更新时间:2023-11-03 19:00:21 24 4
gpt4 key购买 nike

我正在使用以下代码通过 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",
}
]

知道为什么它不起作用吗?

最佳答案

代码产生的输出是预期的输出。您必须将数据转换为您想要的格式。这是一个如何做到这一点的例子:

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);
}

关于c# - 使用 JavaScriptSerializer 将 csv 转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37077000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com