Skip to content

Instantly share code, notes, and snippets.

@BasixKOR
Last active November 28, 2019 06:56
Show Gist options
  • Save BasixKOR/60a915bf35eef94ae6eb1f050aa35a5c to your computer and use it in GitHub Desktop.
Save BasixKOR/60a915bf35eef94ae6eb1f050aa35a5c to your computer and use it in GitHub Desktop.
CSV2JSON

This C code recieves a CSV data from stdin, and returns the result via stdout. You can pipe your data to put and extract both input and output.

Features

  • Supports automatic numberic conversion. (decimal only)
  • Supports real-time output right from stdout.

Limitations

  • Does not support double quoted items (therefore not RFC 4180 compatiable)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define _CRT_SECURE_NO_WARNINGS 1
#define MAX_LINE 400
void convert(wchar_t* item);
wchar_t buffer[MAX_LINE] = { 0 };
wchar_t* tmp;
_Bool flag = 0;
int main(int argc, char** argv) {
printf("[");
while (fgetws(buffer, MAX_LINE, stdin) != NULL) {
if (flag) printf(",");
wchar_t* item = wcstok(buffer, L",", &tmp);
do convert(item); while ((item = wcstok(NULL, L",", &tmp)) != NULL);
printf("]");
flag = 1;
}
printf("]");
}
void convert(wchar_t* item) {
int length = wcslen(item);
wchar_t prefix = L',';
_Bool numberic = 1;
if (item[length - 1] == '\n') item[--length] = 0L;
else if(buffer == item) prefix = L'[';
for (int i = 0; i < length; i++) if (item[i] < L'0' || item[i] > L'9') {
numberic = 0;
break;
}
if(numberic) printf("%c%ls", prefix, item);
else printf("%c\"%ls\"", prefix, item);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment