JSON是一種常用的數(shù)據(jù)格式,它有很多優(yōu)點(diǎn)。在C語(yǔ)言中,可以通過(guò)構(gòu)建一個(gè)JSON來(lái)描述數(shù)據(jù)。以下是如何使用C語(yǔ)言構(gòu)建一個(gè)簡(jiǎn)單的JSON的示例:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_STRING_LEN 256 typedef struct { char *key; char *value; } Node; typedef struct { Node **nodes; int size; } Object; typedef struct { char *data; } String; typedef struct { char *data; } Number; typedef struct { Object *object; } JSON; void add_node_to_object(Object *object, char *key, char *value) { Node *new_node = (Node *) malloc(sizeof(Node)); new_node->key = key; new_node->value = value; object->nodes = (Node **) realloc(object->nodes, sizeof(Node *) * (object->size+1)); object->nodes[object->size] = new_node; object->size++; } Object *create_object() { Object *object = (Object *) malloc(sizeof(Object)); object->nodes = NULL; object->size = 0; return object; } String *create_string(char *data) { String *string = (String *) malloc(sizeof(String)); string->data = data; return string; } Number *create_number(char *data) { Number *number = (Number *) malloc(sizeof(Number)); number->data = data; return number; } JSON *create_json() { JSON *json = (JSON *) malloc(sizeof(JSON)); json->object = create_object(); return json; } void print_json(JSON *json) { int i; Object *object = json->object; printf("{\n"); for(i=0; i<object->size; i++) { printf("\t\"%s\": \"%s\"\n", object->nodes[i]->key, object->nodes[i]->value); } printf("}\n"); } int main() { JSON *json = create_json(); add_node_to_object(json->object, "name", "張三"); add_node_to_object(json->object, "age", "25"); add_node_to_object(json->object, "sex", "男"); print_json(json); return 0; }
上面的代碼中,我們構(gòu)建了一些結(jié)構(gòu)體,包括節(jié)點(diǎn)(Node)、對(duì)象(Object)、字符串(String)、數(shù)字(Number)和JSON。其中,節(jié)點(diǎn)是構(gòu)成對(duì)象的基本單元,而對(duì)象則可以包含多個(gè)節(jié)點(diǎn),節(jié)點(diǎn)按照鍵值對(duì)的形式存儲(chǔ)。字符串和數(shù)字是節(jié)點(diǎn)的具體內(nèi)容。整個(gè)JSON則是一個(gè)對(duì)象。
在主函數(shù)中,我們首先創(chuàng)建了一個(gè)JSON對(duì)象,然后添加了三個(gè)節(jié)點(diǎn),分別表示“姓名”、“年齡”和“性別”。最后,我們將JSON輸出到控制臺(tái),在控制臺(tái)上可以看到一個(gè)合法的JSON字符串。