Skip to content

Instantly share code, notes, and snippets.

@CipherLab
Created July 11, 2014 13:49
Show Gist options
  • Save CipherLab/a012d8eb2b28ca66609e to your computer and use it in GitHub Desktop.
Save CipherLab/a012d8eb2b28ca66609e to your computer and use it in GitHub Desktop.
Convert a csv file to a json obect! Neat!
public static string CsvToJson(string value, char delim, bool hasHeader)
{
// Get lines.
if (value == null) return null;
value = value.Replace("\r\n", "\r");
value = value.Replace("\r", "\r\n");
value = value.Replace(delim, ',');
string[] lines = value.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
if (lines.Length < 2) throw new InvalidDataException("Must have header line.");
// Get headers.
List<string> headers = new List<string>();
int startIdx = 0;
if (hasHeader)
{
headers.AddRange(lines.First().Split(','));
startIdx = 1;
}
else
{
//fix any empty headers
for (int i = 0; i < headers.Count; i++)
{
if (string.IsNullOrEmpty(headers[i]))
{
headers[i] = "Field" + i;
}
}
}
// Build JSON array.
StringBuilder sb = new StringBuilder();
sb.AppendLine("[");
for (int i = startIdx; i < lines.Length; i++)
{
//string[] fields = lines[i].Split(',');
List<string> fields = new List<string>();
var regex = new Regex("(?<=^|,)(\"(?:[^\"]|\"\")*\"|[^,]*)");
foreach (Match m in regex.Matches(lines[i]))
{
fields.Add(m.Value.Replace("\"", ""));
}
int x = headers.Count;
if (fields.Count != headers.Count)
{
while (headers.Count < fields.Count)
{
headers.Add("Field" + x++);
}
//throw new InvalidDataException("Field count must match header count.");
}
var jsonElements = headers.Zip(fields, (header, field) => string.Format("\"{0}\": \"{1}\"", header, field)).ToArray();
string jsonObject = "{" + string.Format("{0}", string.Join(",", jsonElements)) + "}";
if (i < lines.Length - 1)
jsonObject += ",";
sb.AppendLine(jsonObject);
}
sb.AppendLine("]");
return sb.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment