Using CSV Helper you can deserialize to Dynamic, ref doc.
Then you can serialize the result to json using JSON.Net ref.
var txtInput = "a,b,c\n1,2,3\n4,5,6";
string output;
using (var reader = new StringReader(txtInput))
using (var csvReader = new CsvReader(reader, CultureInfo.InvariantCulture))
{
var records = csvReader.GetRecords<dynamic>();
output = JsonConvert.SerializeObject(records, Formatting.Indented);
}
Result:
[
{
"a": "1",
"b": "2",
"c": "3"
},
{
"a": "4",
"b": "5",
"c": "6"
}
]
Live Demo : https://dotnetfiddle.net/lF0zJ2
Note that for CSV file you can use a StreamReader
like :
using (var reader = new StreamReader("path\\to\\file.csv"))
While I don't recommend using dynamic typing. For reading a CSV I will recommend writing the proper class representing the data and the mapping class in order to let CSV Helper do everything: type check, unordered column, missing column, missing header, duplicate name column, different separator, multiline data, quoted field etc etc.
Disclaimer:
This answers doesn't match the given input and ouput. I choosed to take into account only the part that was valid. If you need the ouput to be int instead of string. You can create a class representing the Csv Object (CSV helper Getting Started ).
And use csvReader .GetRecords<MyClass>()
.