Tuesday, March 27, 2012

C# CODE TO CONVERT CSV FILE JSON FILE FORMAT


using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using System.Data;
using System.Text.RegularExpressions;

namespace jsonPractice
{
 
    class Program
    {
        static void Main(string[] args)
        {
            string[] cols;
            string[] rows;
         
            StreamReader sr = new StreamReader(@"F:\Sample.csv");  //SOURCE FILE
            StreamWriter sw = new StreamWriter(@"F:\sample.json");  // DESTINATION FILE
         
            string line = sr.ReadLine();
         

            cols = Regex.Split(line, ",");

            DataTable table = new DataTable();
            for (int i = 0; i < cols.Length; i++)
            {
                table.Columns.Add(cols[i], typeof(string));
            }
            while ((line = sr.ReadLine()) != null)
            {
                 table.Rows.Clear();
             
                int i;
                string row = string.Empty;
                rows = Regex.Split(line, ",");
                DataRow dr = table.NewRow();
             
                for (i = 0; i < rows.Length ; i++)
                {
                    dr[i] = rows[i];
                                   
                }
                table.Rows.Add(dr);
             
                string json = JsonConvert.SerializeObject(table, Formatting.Indented);
                sw.Write(json);
            }

       
            sw.Close();
            sr.Close();

        }
    }
}

2 comments:

  1. Just so you know, you are writing out the entire table but with just a single row, over and over again. One would expect something like:
    [
    {...},
    {...},
    ]

    but instead we get

    [{...}],
    [{...}],

    ReplyDelete
  2. The problem is on

    table.Rows.Clear();

    line. Remove it and all works fine

    ReplyDelete