#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLN 1024
struct node{
char content[MAXLN];
struct node * next;
};
int parsejson(FILE *, FILE *);
struct node * parseline(FILE *, char line[MAXLN], int *, int *, int *, struct node *,
struct node *);
int skipwhsp(char line[MAXLN], int *);
void freelist(struct node *);
int main(void)
{
FILE * f = fopen("convertor.in", "r");
FILE * g = fopen("convertor.out", "w");
parsejson(f, g);
fclose(f);
fclose(g);
return 0;
}
int parsejson(FILE * f, FILE * g) {
struct node * first_val = (struct node *)malloc(sizeof(first_val));
struct node * last_val = first_val;
int no_vals = 0;
char line[MAXLN];
int isatt = 1, isfirstobj = 1, isfirstval = 1;
while(!feof(f)) {
fgets(line, MAXLN, f);
last_val = parseline(g, line, &isfirstobj, &isfirstval, &isatt, first_val,
last_val);
if(last_val == 0) {
break;
}
}
freelist(first_val);
return 0;
}
struct node * parseline(FILE * g, char line[MAXLN], int * isfirstobj, int * isfirstval,
int * isatt, struct node * first_val, struct node * last_val) {
struct node * curr;
char buffer[MAXLN];
int buflen = 0, crt = 0;
skipwhsp(line, &crt);
if(*isfirstobj) {
if(line[crt] == '[') {
crt++;
skipwhsp(line, &crt); //citesc pana la {
}
}
while(crt < strlen(line)) {
//tratam cazul "
if(line[crt] == '"') {
buflen = 0;
crt++;
while(line[crt] != '"') {
buffer[buflen++] = line[crt++];
}
buffer[buflen++] = '\0';
crt++;
if(*isatt) {
if(*isfirstobj) {
fprintf(g, "%s,", buffer);
}
} else {
if(!(*isfirstval)) {
if(*isfirstobj) {
last_val->next = (struct node *)malloc(sizeof(struct node));
}
last_val = last_val->next;
} else {
*isfirstval = 0;
}
strcpy(last_val->content, buffer);
}
*isatt = 1 - *isatt; // printf("%s\n", buffer);
} else if(line[crt] >= '0' && line[crt] <= '9') {
//tratam cazul 0-9; sigur e valoare
buflen = 0;
while('0' <= line[crt] && '9' >= line[crt]) {
buffer[buflen++] = line[crt++];
}
buffer[buflen++] = '\0';
crt++;
//pune in lista
if(!(*isfirstval)) {
if(*isfirstobj) {
last_val->next = (struct node *)malloc(sizeof(struct node));
}
last_val = last_val->next;
} else {
*isfirstval = 0;
}
strcpy(last_val->content, buffer);
*isatt = 1;
} else if(strchr(",:{", line[crt]) != NULL) {
//peste {, : si , trecem
crt++;
} else if(line[crt] == '}') {
//tratam cazul }
fprintf(g, "\n");
curr = first_val;
while(curr != NULL) {
fprintf(g, "%s,", curr->content);
curr = curr->next;
}
*isfirstobj = 0;
*isfirstval = 1;
last_val = first_val;
crt++;
} else if(line[crt] == ']') {
return 0;
}
skipwhsp(line, &crt);
}
return last_val;
}
int skipwhsp(char line[MAXLN], int * crt) {
while(strchr(" \t\n", line[*crt]) != NULL) {
(*crt)++;
}
return *crt;
}
void freelist(struct node * first) {
struct node * ante = first;
struct node * curr = ante->next;
while(ante != NULL) {
free(ante);
ante = curr;
if(curr != NULL) {
curr = curr->next;
}
}
}