#CognitiveServices – Easy lines to convert CSV to JSON to be used on the #AnomalyDetector service

Buy Me A Coffee


After the event “Building an Anomaly Detector System with a few or no lines of code” at MsftReactor, some people asked for the 2 lines that I used to convert a CSV file to JSON, to be used with Cognitive Services Anomaly Detector, so here they are.

static string CsvToJson(string csvPath, string granularity = "daily", bool hasHeaders = true)
char[] fieldSeparator = { ',' };
var lines = System.IO.File.ReadAllLines(csvPath);
// remove header
if (hasHeaders)
lines = lines.Skip(1).ToArray();
// build series
var arraySeries = new JArray();
foreach (var line in lines)
if (string.IsNullOrEmpty(line)) continue;
var fields = line.Split(fieldSeparator);
var jsonSerie = new JObject
["timestamp"] = fields[0],
["value"] = fields[1]
var jobjectMain = new JObject
["granularity"] = granularity,
["series"] = arraySeries,
var jsonComplete = new JArray {jobjectMain};
return jsonComplete.ToString();

Important: you need Newtonsoft.Json to build the json content.

The input CSV is part of the Machine Learning.Net sample data, and has this sample content:


And as a bonus, the full console project can be downloaded from here.


This project also have a second function which creates the JSON content using simple string, without the need of Newtonsoft.Json.

Happy coding!

Greetings @ Burlingon

El Bruno



1 comment

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: