gpt4 book ai didi

C# 将 CSV 解析为 JSON 格式错误

转载 作者:行者123 更新时间:2023-12-02 22:09:59 25 4
gpt4 key购买 nike

看一看,让我知道我到底在搞什么鬼 ;)

[HttpPost]
public ActionResult Upload(HttpPostedFileBase File)
{

HttpPostedFileBase csvFile = Request.Files["adGroupCSV"];

byte[] buffer = new byte[csvFile.ContentLength];
csvFile.InputStream.Read(buffer, 0, csvFile.ContentLength);

string csvString = System.Text.Encoding.UTF8.GetString(buffer);

string[] lines = Regex.Split(csvString, "\r");
List<string[]> csv = new List<string[]>();

foreach (string line in lines)
{
csv.Add(line.Split(','));
}

string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(csv);

ViewData["CSV"] = json;

return View(ViewData);
}

是这样的:

json = "[[\"Col1\",\"Col2\",\"Col3\",\"Col4\",\"Col5\",\"Col6\"],[\"test\",\"test\",\"test\",\"test\",\"http://www.test.com/\",\"test/\"],[\"test\",\"test\",\"test\",\"test\",\"http://www.test.com...

这就是我想要的:

{"Col1":"test","Col2":"test","Col3":"test","Col4":"test","Col5":"http://www.test.com/","Col6":"test/"}

这是 CSV 的示例

Col1,Col2,Col3,Col4,Col5,Col6
Test1,Test1,Test1,test1,test.test,test/
Test2,Test2,Test2,test2,test.test,test/
Test3,Test3,Test3,test3,test.test,test/
Test4,Test4,Test4,test4,test.test,test/

最佳答案

你需要一本字典。只需更换

List<string[]> csv = new List<string[]>();

foreach (string line in lines)
{
csv.Add(line.Split(','));
}

var csv = lines.Select(l => l.Split(',')
.Select((s,i)=>new {s,i})
.ToDictionary(x=>"Col" + (x.i+1), x=>x.s));

它应该工作...

编辑

var lines = csvString.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
var cols = lines[0].Split(',');
var csv = lines.Skip(1)
.Select(l => l.Split(',')
.Select((s, i) => new {s,i})
.ToDictionary(x=>cols[x.i],x=>x.s));

var json = new JavaScriptSerializer().Serialize(csv);

关于C# 将 CSV 解析为 JSON 格式错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15484060/

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