0

I am trying to convert csv data into json data format.

I wrote code as below. How to convert below data as json format data

string csvData = File.ReadAllText(csvPath);

//Execute a loop over the rows.

foreach (string row in csvData.Split('\n'))
{
    if (!string.IsNullOrEmpty(row))
    {
        dt.Rows.Add();
        int i = 0;
        //Execute a loop over the columns.  
        foreach (string cell in row.Split(','))
        {
            dt.Rows[dt.Rows.Count - 1][i] = cell;
            Console.WriteLine(dt.Rows[dt.Rows.Count - 1][i]);
            i++;
        }
    }
    var telemetryDataPoint = row;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
krishna bh
  • 81
  • 2
  • 9
  • 3
    Possible duplicate of [Converting a csv file to json using C#](https://stackoverflow.com/questions/10824165/converting-a-csv-file-to-json-using-c-sharp) – MethodMan Nov 27 '17 at 17:59
  • CSV text files come with so many questions. If you have Excel, go Data»Get External Data»From Text and select a text file. Run through the Text Import Wizard. You should have an answer to every question and put that knowledge into code, as applicable. – Tom Blodget Nov 27 '17 at 18:20

1 Answers1

0

Try this:

foreach (string row in csvData.Split('\n'))
{
  if (!string.IsNullOrEmpty(row))
  {
    string jsonString = new 
System.Web.Script.Serialization.JavaScriptSerializer().Serialize(row); //Per row
    dt.Rows.Add();
    int i = 0;
    //Execute a loop over the columns.  
    foreach (string cell in row.Split(','))
    {
      dt.Rows[dt.Rows.Count - 1][i] = cell;
      Console.WriteLine(dt.Rows[dt.Rows.Count - 1][i]);
      i++;
    }
  }
  var telemetryDataPoint = row;
}

OR

// All at once
var data = (from row in csvData.Split('\n')
            select row.Split(',')).ToList();
string jsonString = new 
System.Web.Script.Serialization.JavaScriptSerializer().Serialize(data);
Sunil
  • 3,404
  • 10
  • 23
  • 31