C語言是一種廣泛應用于系統編程和嵌入式設備控制的編程語言。而在現代開發中,JSON(JavaScript對象表示法)作為數據交換格式也已經成為了主流。那么在C語言中,如何去拼接JSON數據呢?
#include#include #include #include #define BUFSIZE 256 /* 向buffer拼接key-value對 */ void add_kv(char *buffer, char *key, char *value) { strcat(buffer, "\""); strcat(buffer, key); strcat(buffer, "\":\""); strcat(buffer, value); strcat(buffer, "\","); } /* 向buffer拼接數組 */ void add_arr(char *buffer, char *key, char **values, size_t len) { strcat(buffer, "\""); strcat(buffer, key); strcat(buffer, "\":["); for (size_t i = 0; i< len; i++) { strcat(buffer, "\""); strcat(buffer, values[i]); strcat(buffer, "\""); if (i + 1< len) { strcat(buffer, ","); } } strcat(buffer, "],"); } /* 根據參數生成JSON字符串 */ char *generate_json(char *category, char *name, char *age, char *langs[], size_t lang_len) { char *buffer = malloc(BUFSIZE); strcpy(buffer, "{"); add_kv(buffer, "Category", category); add_kv(buffer, "Name", name); add_kv(buffer, "Age", age); add_arr(buffer, "Languages", langs, lang_len); strcat(buffer, "\"\":null}"); // 最后一個key-value pair要特殊處理 return buffer; } int main() { char *langs[] = {"C", "Python", "JavaScript"}; size_t lang_len = 3; char *json_str = generate_json("Person", "Tom", "20", langs, lang_len); printf("%s\n", json_str); free(json_str); return 0; }
以上代碼實現了一個簡單的JSON拼接函數。通過向buffer參數不斷拼接key-value對和數組,最后得到完整的JSON字符串。在生成完JSON字符串之后,我們可以將其發送到服務器或從文件中讀取并解析。