Converting a csv file to json using C#

后端 未结 14 1656
余生分开走
余生分开走 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:45

    Simple method to convert flat csv file to a collection of simple json formatted objects. Works with files with header row on the first line. Part of this method was found somewhere else on SO. Add reference to Microsoft.VisualBasic.

    using Microsoft.VisualBasic.FileIO;
    public static StringBuilder ReadCsv()
        {
            var path = @"X:\...\input.csv";
            using (TextFieldParser csvParser = new TextFieldParser(path))
            {
                csvParser.CommentTokens = new string[] { "#" };
                //Remember to use your own separator
                csvParser.SetDelimiters(new string[] { ";" });
                csvParser.HasFieldsEnclosedInQuotes = false;
    
                StringBuilder json = new StringBuilder();
                string[] colNames = new string[0];
                string[] fields = new string[0];
    
                json.Append("[");
    
                int counter = 0;
                while (!csvParser.EndOfData)
                {
                    if (counter == 0)
                    {
                        //Read properies' names
                        colNames = csvParser.ReadFields();
                        counter++;
                        Console.WriteLine($"{colNames.Length} columns detected!");
                    }
                    else
                    {
                        // Read current line fields, pointer moves to the next line.
                        // Read the properties' values
                        fields = csvParser.ReadFields();
    
                        json.Append("{");
    
                        for (int i = 0; i < colNames.Length; i++)
                        {
                            json.Append($"\"{colNames[i]}\":{TryParse(fields[i])}");
                            if (i != colNames.Length - 1)
                            {
                                json.Append(",");
                            }
                        }
                        json.Append("},");
                        Console.WriteLine($"Writing record nr.: {counter}");
                        counter++;
                    }
                }
                json.Length--; //Remove trailing comma
                json.Append("]");
                return json;
            }
        }
    
    string TryParse(string s)
        {
            if (string.IsNullOrEmpty(s)) return "null";
            //Remember to set your decimal character here!
            if (s.Contains('.'))
            {
                double dResult;
                //This works on my computer, could be different on your machine
                if (double.TryParse(s, NumberStyles.AllowDecimalPoint,
                                    CultureInfo.InvariantCulture, out dResult))
                    return dResult.ToString(CultureInfo.InvariantCulture);
            }
            else
            {
                int intResult;
                if (int.TryParse(s, out intResult))
                    return intResult.ToString(CultureInfo.InvariantCulture);
            }
            return "\"" + s + "\"";
        }
    

    This should give you a simple list of json objects.

提交回复
热议问题