cJSON库解析

前端之家收集整理的这篇文章主要介绍了cJSON库解析前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

最近在使用c语言来编写服务器。json又是比较常用的一种配置说明文件的格式。来记录一下。以资查阅。实在太简单了。
(下载地址)[https://sourceforge.net/projects/cjson/]

对于cJSON中的节点描述:

/* The cJSON structure: */
typedef struct cJSON {
    struct cJSON *next,*prev;   /* next/prev allow you to walk array/object chains. Alternatively,use GetArraySize/GetArrayItem/GetObjectItem */
    struct cJSON *child;        /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */

    int type;                   /* The type of the item,as above. */

    char *valuestring;          /* The item's string,if type==cJSON_String */
    int valueint;               /* The item's number,if type==cJSON_Number */
    double valuedouble;         /* The item's number,if type==cJSON_Number */

    char *string;               /* The item's name string,if this item is the child of,or is in the list of subitems of an object. */
} cJSON;

将内存解析json

/* Supply a block of JSON,and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
extern cJSON *cJSON_Parse(const char *value);

如果需要加载的json为

{
    "first_blood" : { "jax" : true },"second_blood" : { "Vayne" : true } }
cJSON *cjson   = NULL;
    cjson = cJSON_Parse(buf);
    cJSON *node    = NULL;
    cJSON *ele     = NULL;
    if (cjson == NULL) {
        printf("[IDL] load_idl_file Failed,parse file Failed,info: %s\n",cfg);
        return 1;
    }
    for ( node = cjson->child; node != NULL; node = node->next) {
        fun_name = node->string;
        ele      = node->child;
        printf("name: %s\n",ele->string);
    }

这样也就受用了。

猜你在找的Json相关文章