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;
}
2
  • 3
    Possible duplicate of Converting a csv file to json using C# Commented Nov 27, 2017 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. Commented Nov 27, 2017 at 18:20

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.