Converting a csv file to json using C#

后端 未结 14 1699
余生分开走
余生分开走 2020-12-04 22:10

I was wondering if someone\'s written a utility to convert a CSV file to Json using C#. From a previous question on stackoverflow, I\'m aware of this nice utility - https://

14条回答
  •  醉酒成梦
    2020-12-04 22:46

    Here's mine.. It can parse 9k CSV records in centuries. LOL

    class CSVTOJSON
    {
        public string ConvertToJSON()
        {
            string json = string.Empty;
            string csv = string.Empty;
    
            using (StreamReader reader = new StreamReader("data.csv"))
            {
                csv = reader.ReadToEnd();
            }
    
            string[] lines = csv.Split(new string[] { "\n" }, System.StringSplitOptions.None);
    
            if (lines.Length > 1)
            {
                // parse headers
                string[] headers = lines[0].Split(',');
    
                StringBuilder sbjson = new StringBuilder();
                sbjson.Clear();
                sbjson.Append("[");
    
                // parse data
                for (int i = 1; i < lines.Length; i++)
                {
                    if (string.IsNullOrWhiteSpace(lines[i])) continue;
                    if (string.IsNullOrEmpty(lines[i])) continue;
    
                    sbjson.Append("{");
    
                    string[] data = lines[i].Split(',');
    
                    for (int h = 0; h < headers.Length; h++)
                    {
                        sbjson.Append(
                            $"\"{headers[h]}\": \"{data[h]}\"" + (h < headers.Length - 1 ? "," : null)
                        );
                    }
    
                    sbjson.Append("}" + (i < lines.Length - 1 ? "," : null));
                }
    
                sbjson.Append("]");
    
                json = sbjson.ToString();
            }
    
            return json;
        }
    }
    

    But it works.

    console log:

    Converting CSV to JSON
    CSV has 9486 data
    Total duration converting CSV to JSON: 00:00:00.0775373
    

提交回复
热议问题