Can anyone help in writing a C parser (using Codewarrior) to parse the following file? I tried many C language json parser, but unfortunately didn't get the idea or they make it difficult.
[
[0,"Door1","Door1Drv","Calculator","Alarm"],
[1,"Door3","Door3Drv","Calculator","Alarm"],
[2,"Door2","Door2Drv","Calculator","Alarm"]]
For advance application, recommend to use Frozen. If your application has fix data format as shown above, see below for your ref.
Quite basic version look like below:
#include <stdio.h>
#define MAX_PRAM 4
struct param_t {
int id;
// FIXME: use pointer & malloc to allocate if possible
char data[MAX_PRAM][30];
};
static int parse(const char *buff, int start, const int end,
struct param_t *out)
{
char *ptr = out->data[0];
int state = 0;
int index = 0;
int param_index = 0;
printf("\t> parse next record<%d:%d>\n", start, end);
while((start < end) && (param_index < MAX_PRAM)) {
char ch = buff[start];
// printf("\t> state: %d, char '%c'\n", state, ch);
switch (state) {
case 0: // searching for start point
if ((ch >= '0') && (ch <= '9')) {
out->id = ch - '0';
state++;
}
break;
case 1: // parse number
if ((ch < '0') || (ch > '9')) {
printf ("\t> number %d\n", out->id);
state++;
if (ch == '"')
state++;
} else
out->id = (out->id * 10) + (ch - '0');
break;
case 2: // search string
if (ch == '"') {
index = 0;
state++;
}
break;
case 3: // get string
if (ch == '"') { // finish one string, parse next one if need
ptr[index] = '\0';
printf ("\t> string '%s', length %d\n",
out->data[param_index], index);
param_index++;
ptr = out->data[param_index];
state--;
} else
ptr[index++] = ch;
break;
default: // EOS - exit
break;
}
start++;
}
return (param_index >= 4) ? start : 0;
}
//
// main entry
//
int main(int argc, char *argv[]) {
int file = open("test.txt", 0 /* 0 ~ O_RDONLY in fcntl.h */ );
if (file) {
char buff[1024] = { 0 };
struct param_t param = { 0 };
int len = read(file, buff, 1024);
int pos = 0;
while((pos = parse(buff, pos, len, ¶m)) > 0) {
printf ("\t%d\n", param.id);
printf("[%4d] %d - %-10s | %-10s | %-15s | %-10s \n",
pos, param.id, param.data[0], param.data[1], param.data[2],
param.data[3]);
}
close(file);
}
}
With input:
[[10,"Door0",
"Door0Drv","Calculator0","Alarm0"],
[15,"Door1","Door1Drv","Calculator1","Alarm1"],
[230,"Door2","Door2Drv","Calculator2",
"Alarm2"]]
Output looks like:
> number 10
> string 'Door0', length 5
> string 'Door0Drv', length 8
> string 'Calculator0', length 11
> string 'Alarm0', length 6
10
[ 49] 10 - Door0 | Door0Drv | Calculator0 | Alarm0
> number 15
> string 'Door1', length 5
> string 'Door1Drv', length 8
> string 'Calculator1', length 11
> string 'Alarm1', length 6
15
[ 100] 15 - Door1 | Door1Drv | Calculator1 | Alarm1
> number 230
> string 'Door2', length 5
> string 'Door2Drv', length 8
> string 'Calculator2', length 11
> string 'Alarm2', length 6
230
[ 158] 230 - Door2 | Door2Drv | Calculator2 | Alarm2
Feel free to customize.