Skip to content

Instantly share code, notes, and snippets.

@nertim
Created December 11, 2017 23:40
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nertim/1367ef1cc4a339b105c6d72aafd7bff4 to your computer and use it in GitHub Desktop.
Save nertim/1367ef1cc4a339b105c6d72aafd7bff4 to your computer and use it in GitHub Desktop.
CSV To Json Array Azure Function
#r "newtonsoft.json"
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Net;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
var csvContent = await req.Content.ReadAsStringAsync();
var csvContentLines = csvContent.Split(
new[] { Environment.NewLine },
StringSplitOptions.None
);
var jsonArray = GetJsonArray(
header: csvContentLines.First(),
csvLines: csvContentLines.Skip(1).ToArray()
);
return req.CreateResponse(HttpStatusCode.OK, jsonArray);
}
private static JArray GetJsonArray(string header, string[] csvLines, char delimiter = ',')
{
if (!csvLines.Any())
{
return new JArray();
}
if (string.IsNullOrEmpty(header))
{
throw new ArgumentException(paramName: nameof(header), message: "Cannot be null or empty.");
}
var headerParts = header.Split(delimiter);
if (headerParts.GroupBy(part => part).Where(partGroup => partGroup.Count() > 1).Any())
{
throw new InvalidOperationException($"There are repeating headers in '{header}'");
}
var jsonArray = new JArray();
foreach (var line in csvLines)
{
var csvParts = line.Split(delimiter);
if (csvParts.Count() != headerParts.Count())
{
throw new InvalidOperationException($"The columns in CSV line '{line}' does not match the header '{header}'");
}
jsonArray.Add(GetJObject(headerParts, csvParts));
}
return jsonArray;
}
private static JObject GetJObject(string[] headerParts, string[] rowParts)
{
var jsonObject = new JObject();
for (var i = 0; i < headerParts.Count(); i++)
{
jsonObject.Add(headerParts[i], rowParts[i]);
}
return jsonObject;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment