Last active
August 29, 2015 14:11
-
-
Save kangear/1d916359b00c32e8cdf6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
/** | |
* @author [email protected] | |
* @data 2014-12-17 | |
* @param dst name num | |
* @return boolean | |
* such as:[{"name1":1, "name2":2}] | |
*/ | |
#define JSON_BUFFER_SIZE 1024 | |
int add_json(char* dst, const char* name, const int num) { | |
const char* const head = "[{"; | |
const char* const end = "}]"; | |
char *p_dst = NULL; | |
int first_time = 0; | |
if (name == NULL) | |
goto err; | |
/* redirect */ | |
p_dst = dst + strlen(dst); | |
/* is first time in here */ | |
if (strlen(dst) < 4) { | |
first_time = 1; | |
} | |
/* add "[{" start or remove '}]' */ | |
if (first_time == 1) { | |
strncpy(p_dst, head, strlen(head)); | |
p_dst += strlen(head); | |
} else { | |
p_dst -= strlen(end); | |
sprintf(p_dst, "%s", ","); | |
p_dst += 1; | |
} | |
/* insert new string */ | |
p_dst += sprintf(p_dst, "\"%s\":%d", name, num); | |
/* add '}]' at end */ | |
sprintf(p_dst, "%s", end); | |
return EXIT_SUCCESS; | |
err: | |
return EXIT_FAILURE; | |
} | |
int main() { | |
//char buf[256] = "[{\"name1\":1, \"name2\":2}]"; | |
char buf[256] = {0}; | |
add_json(buf, "Black", 60); | |
add_json(buf, "Color", 70); | |
add_json(buf, "name3", 4); | |
printf("%s\n", buf); | |
} | |
/** | |
* [{"Black:":100,"Color:":70}] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment