Skip to content

Instantly share code, notes, and snippets.

@kangear
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kangear/1d916359b00c32e8cdf6 to your computer and use it in GitHub Desktop.
Save kangear/1d916359b00c32e8cdf6 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/**
* @author kangear@163.com
* @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