c 自動拼接json類是一種非常有用的工具,它可以幫助我們自動拼接json格式的數據,從而方便我們進行數據傳遞和處理。
#include#include #include #define BUF_SIZE 1024 typedef struct JSON_ITEM { char *key; char *value; struct JSON_ITEM *next; } json_item; typedef struct JSON { json_item *head; json_item *tail; } json; json *new_json() { json *j = (json*)malloc(sizeof(json)); j->head = NULL; j->tail = NULL; return j; } void json_free(json *j) { json_item *cur = j->head; while (cur != NULL) { free(cur->key); free(cur->value); json_item *next = cur->next; free(cur); cur = next; } free(j); } void json_add_item(json *j, const char *key, const char *value) { json_item *item = (json_item*)malloc(sizeof(json_item)); item->key = strdup(key); item->value = strdup(value); item->next = NULL; if (j->head == NULL) { j->head = item; j->tail = item; } else { j->tail->next = item; j->tail = item; } } void json_print(json *j) { printf("{"); json_item *cur = j->head; while (cur != NULL) { printf("\"%s\":\"%s\"", cur->key, cur->value); cur = cur->next; if (cur != NULL) { printf(","); } } printf("}\n"); } char *json_to_string(json *j) { size_t len = 0; json_item *cur = j->head; while (cur != NULL) { len += strlen(cur->key) + strlen(cur->value) + 5; cur = cur->next; } char *buf = (char*)malloc(len + 1); if (buf == NULL) { return NULL; } char *p = buf; *p++ = '{'; cur = j->head; while (cur != NULL) { p += sprintf(p, "\"%s\":\"%s\"", cur->key, cur->value); cur = cur->next; if (cur != NULL) { *p++ = ','; } } *p++ = '}'; *p = '\0'; return buf; } int main() { json *j = new_json(); json_add_item(j, "name", "Alice"); json_add_item(j, "age", "18"); json_add_item(j, "gender", "female"); json_print(j); char *str = json_to_string(j); printf("%s\n", str); free(str); json_free(j); return 0; }
代碼中使用了兩個結構體:json和json_item,分別用來表示整個json和其中的每個條目。使用方式很簡單,只需要調用json_add_item函數來添加條目,然后調用json_to_string函數將json轉化為字符串即可。