Converting a csv file to json using C#

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

    From that same SO answer, there is a link to this post.

    CsvToJson extention method

    /// 
    /// Converts a CSV string to a Json array format.
    /// 
    /// First line in CSV must be a header with field name columns.
    /// 
    /// 
    public static string CsvToJson(this string value)
    {
        // Get lines.
        if (value == null) return null;
        string[] lines = value.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
        if (lines.Length < 2) throw new InvalidDataException("Must have header line.");
    
        // Get headers.
        string[] headers = lines.First().SplitQuotedLine(new char[] { ',' }, false);
    
        // Build JSON array.
        StringBuilder sb = new StringBuilder();
        sb.AppendLine("[");
        for (int i = 1; i < lines.Length; i++)
        {
            string[] fields = lines[i].SplitQuotedLine(new char[] { ',', ' ' }, true, '"', false);
            if (fields.Length != headers.Length) throw new InvalidDataException("Field count must match header count.");
            var jsonElements = headers.Zip(fields, (header, field) => string.Format("{0}: {1}", header, field)).ToArray();
            string jsonObject = "{" + string.Format("{0}", string.Join(",", jsonElements)) + "}";
            if (i < lines.Length - 1)
                jsonObject += ",";
            sb.AppendLine(jsonObject);
        }
        sb.AppendLine("]");
        return sb.ToString();
    }
    

    There appears to be an issue with where some methods called within the above extension live (see the comments of the original blog post), but it should get you most of the way there.

    EDIT Here is another SO answer about splitting a CSV line. You could use one of the suggested regex solutions to create your own SplitQuotedLine method:

    public static string SplitQuotedLine(this string value, char separator, bool quotes) {
        // Use the "quotes" bool if you need to keep/strip the quotes or something...
        var s = new StringBuilder();
        var regex = new Regex("(?<=^|,)(\"(?:[^\"]|\"\")*\"|[^,]*)");
        foreach (Match m in regex.Matches(value)) {
            s.Append(m.Value);
        }
        return s.ToString();
    }
    

    I did not test the above, so forgive me if I made any errors.

    Also, it would appear that Zip is a LINQ extension method, so that takes care of that problem.

提交回复
热议问题