微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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);
    }

这样也就受用了。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐