Skip to content

Instantly share code, notes, and snippets.

@kkrolikowski
Created Mar 10, 2016
Embed
What would you like to do?
json string extraction
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct www {
char * srv_name;
char * srv_alias;
char * doc_root;
} www;
char * jsonVal(const char * json, const char * pattern);
int main(int argc, char *argv[]) {
www data;
char buff[2048] = "[{datatype:www,package:{srv_name:angrybits.pl,srv_alias:www.angrybits.pl,doc_root:/var/www/angrybits.pl/htdocs}}]";
char * datatype = jsonVal(buff, "datatype:");
if(!strcmp(datatype, "www")) {
data.srv_name = jsonVal(buff, "srv_name:");
data.srv_alias = jsonVal(buff, "srv_alias:");
data.doc_root = jsonVal(buff, "doc_root:");
printf("<VirtualHost *:80>\n");
printf(" ServerName %s\n", data.srv_name);
printf(" ServerAlias %s\n", data.srv_alias);
printf(" DocumentRoot %s\n", data.doc_root);
}
free(datatype);
return 0;
}
char * jsonVal(const char * json, const char * pattern) {
char * val = NULL;
size_t pattern_len = strlen(pattern);
const char * val_pos = strstr(json, pattern) + pattern_len;
int i = 0;
size_t len = 0;
char tmp[512];
memset(tmp, '\0', 512);
while(*val_pos != ',' && *val_pos != '}') {
tmp[i] = *val_pos;
val_pos++;
i++;
}
len = strlen(tmp) + 1;
val = (char *) malloc(len * sizeof(char));
strcpy(val, tmp);
return val;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment