简体   繁体   English

csv为json文件格式

[英]csv to json file format

I want to convert my csv file into .json format using c#. 我想使用c#将csv文件转换为.json格式。 here what i have tried: 这是我尝试过的:

var lines = @"text,intentName,entityLabels
        1,2,null
        2,1,null".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);
    Result1.Text = json;

The result is : 结果是:

[
 {
"text":" 1",
"intentName":"2",
"entityLabels":"null"
},
 {
"text":"2",
"intentName":"1",
"entityLabels":"null"
}
] 

it almost like I expected, however I want to make if the entityLabels column is null, then it replace into []. 它几乎像我预期的那样,但是我想使entityLabels列为null,然后将其替换为[]。 so the output that I expecting is: 所以我期望的输出是:

[
 {
"text":" 1",
"intentName":"2",
"entityLabels":[]
},
 {
"text":"2",
"intentName":"1",
"entityLabels":[]
}
] 

anyone know how to do it? 有人知道怎么做吗?

With external lib Cinchoo ETL - an open source library, you can convert CSV --> JSON with the expected format as below 使用外部库Cinchoo ETL-一个开放源代码库,您可以将CSV- > JSON转换为预期格式,如下所示

Method 1: 方法1:

string csv = @"text,intentName,entityLabels
1,2,null
2,1,null
";

StringBuilder sb = new StringBuilder();
using (var p = ChoCSVReader.LoadText(csv)
    .WithFirstLineHeader()
    .WithField("text")
    .WithField("intentName")
    .WithField("entityLabels", fieldType: typeof(int[]), nullValue: "null")
    )
{
    using (var w = new ChoJSONWriter(sb)
        )
        w.Write(p);
}

Console.WriteLine(sb.ToString());

Method 2: 方法2:

string csv = @"text,intentName,entityLabels
1,2,null
2,1,null
";

StringBuilder sb = new StringBuilder();
using (var p = ChoCSVReader.LoadText(csv)
    .WithFirstLineHeader()
    .WithField("text")
    .WithField("intentName")
    .WithField("entityLabels", valueConverter: (o) => new int[] { })
    )
{
    using (var w = new ChoJSONWriter(sb)
        )
        w.Write(p);
}

Console.WriteLine(sb.ToString());

Output: 输出:

[
 {
  "text": "1",
  "intentName": "2",
  "entityLabels": []
 },
 {
  "text": "2",
  "intentName": "1",
  "entityLabels": []
 }
]

Hope it helps. 希望能帮助到你。

Don't try to use string operations to convert from one data type to another. 不要尝试使用字符串操作将一种数据类型转换为另一种数据类型。

Instead use an actual CSV parsing library like csvhelper (available on NuGet) to deserialise the CSV into objects, and then re-serialise that same data as JSON using a JSON serializer. 而是使用实际的CSV解析库(如csvhelper(在NuGet上提供))将CSV反序列化为对象,然后使用JSON序列化器将与JSON相同的数据重新序列化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM