Converting a csv file to json using C#

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

    /// <summary>
    /// Converts a CSV string to a Json array format.
    /// </summary>
    /// <remarks>First line in CSV must be a header with field name columns.</remarks>
    /// <param name="value"></param>
    /// <returns></returns>
    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.

    0 讨论(0)
  • 2020-12-04 22:55

    I looked for the answer for this question finally i solved it by using Dictionary

    public static void CreateJsonFromCSV()
    {
        string path = "C:\\Users\\xx\\xx\\xx\\xx\\lang.csv";
        string textFilePath = path;
        const Int32 BufferSize = 128;
    
        using (var fileStream = File.OpenRead(textFilePath))
        using (var streamReader = new StreamReader(fileStream, Encoding.UTF8, true, BufferSize))
        {
            String line;
            Dictionary<string, string> jsonRow = new Dictionary<string, string>();
    
            while ((line = streamReader.ReadLine()) != null)
            {
    
                string[] parts = line.Split(',');
    
                string key_ = parts[0];
                string value = parts[1];
    
    
                if (!jsonRow.Keys.Contains(key_))
                {
                    jsonRow.Add(key_, value );
                }
    
            }
            var json = new JavaScriptSerializer().Serialize(jsonRow);
            string path_ = "C:\\XX\\XX\\XX\\XX\\XX.csv";
            File.WriteAllText(path_, json);
        }
    
    } 
    
    0 讨论(0)
提交回复
热议问题