Created
February 5, 2020 03:11
-
-
Save adlerpagliarini/11aaeb86eb0845a1124260512617ab68 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://www.codeproject.com/Questions/1128427/JSON-to-CSV-converter | |
public static class JsonToCsv | |
{ | |
public static void JsonStringToCSV(string jsonContent) | |
{ | |
XmlNode xml = JsonConvert.DeserializeXmlNode("{records:{record:" + jsonContent + "}}"); | |
XmlDocument xmldoc = new XmlDocument(); | |
xmldoc.LoadXml(xml.InnerXml); | |
XmlReader xmlReader = new XmlNodeReader(xml); | |
DataSet dataSet = new DataSet(); | |
dataSet.ReadXml(xmlReader); | |
var dataTable = dataSet.Tables[0]; | |
//Datatable to CSV | |
var lines = new List<string>(); | |
string[] columnNames = dataTable.Columns.Cast<DataColumn>(). | |
Select(column => column.ColumnName). | |
ToArray(); | |
var header = string.Join(",", columnNames); | |
lines.Add(header); | |
var valueLines = dataTable.AsEnumerable() | |
.Select(row => string.Join(",", row.ItemArray)); | |
lines.AddRange(valueLines); | |
File.WriteAllLines($"./data_{Guid.NewGuid()}.csv", lines); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment