ANSI C中的超轻量级JSON解析器
JSON(JavaScript对象表示法)是一种轻量级的数据交换格式。人类易于阅读和书写。机器很容易解析和生成。它基于JavaScript编程语言标准ECMA-262第三版(1999年12月)的子集 。JSON是一种完全独立于语言的文本格式,但是使用C语言家族(包括C,C ++,C#,Java,JavaScript,Perl,Python等)的程序员熟悉的约定。这些属性使JSON成为理想的数据交换语言。
cJSON旨在成为您可以完成工作的最简单的解析器。它是资源只有一个C的头文件和C文件,所以方便移植。它可以为你各种需要的json字符串处理,包括打包、解析、修改、删除、添加等。在这里将一探究竟。
在这里将着重叙述json的打包和解析,更多处理玩法,见文章末尾链接。
开始cJSON
cJSON合并到您的项目
因为整个库只有一个C文件和一个头文件,所以您只需复制cJSON.h并复制cJSON.c到项目源并开始使用它。
cJSON用ANSI C(C89)编写,以便支持尽可能多的平台和编译器。
下载:
https://github.com/DaveGamble/cJSON/releases
Cjson结构体
/* The cJSON structure: */ typedef struct cJSON { struct cJSON *next; struct cJSON *prev; struct cJSON *child; int type; char *valuestring; int valueint; double valuedouble; char *string; } cJSON;
结构体项解析:
next 和prev :Cjson结构体作为一个双向连表的环,可以通过 next 和prev 指针进行连表遍历
child:可以是cJSON_Array、cJSON_Object类型数据
type:当前项的类型
valuestring:内容存储,当类型是cJSON_String和cJSON_Raw
valueint:内容存储,整型,可以是cJSON_False、cJSON_True数据
valuedouble:内容存储,浮点型,当类型是cJSON_Number
string:键名
数据类型
l cJSON_Invalid表示一个不包含任何值的无效项目。如果将项目设置为全零字节,则将自动具有此类型。
l cJSON_False表示一个false布尔值。您也可以使用来检查布尔值cJSON_IsBool
l cJSON_True表示一个true布尔值。您也可以使用来检查布尔值cJSON_IsBool
l cJSON_NULL表示一个null值
l cJSON_Number 表示一个数字值。该值存储为double in valuedouble和in valueint。如果数字超出整数范围,INT_MAX或INT_MIN用于valueint
l cJSON_String表示一个字符串值。它以零终止字符串的形式存储在中valuestring
l cJSON_Array表示一个数组值。这是通过指向表示数组中值child的cJSON项目的链接列表来实现的。使用next和将元素链接在一起prev,其中第一个元素具有prev.next == NULL和最后一个元素next == NULL
l cJSON_Object 表示一个对象值。对象的存储方式与数组相同,唯一的区别是对象中的项将其键存储在中string
l cJSON_Raw表示以JSON字符存储的零终止形式的任何JSON valuestring。例如,可以使用它来避免一遍又一遍地打印相同的静态JSON以节省性能。解析时,cJSON永远不会创建此类型。另请注意,cJSON不会检查其是否为有效JSON。
类型
#define cJSON_Invalid (0) #define cJSON_False (1 << 0) #define cJSON_True (1 << 1) #define cJSON_NULL (1 << 2) #define cJSON_Number (1 << 3) #define cJSON_String (1 << 4) #define cJSON_Array (1 << 5) #define cJSON_Object (1 << 6) #define cJSON_Raw (1 << 7) /* raw json */
类型判断
cJSON_IsInvalid(const cJSON * const item); cJSON_IsFalse(const cJSON * const item); cJSON_IsTrue(const cJSON * const item); cJSON_IsBool(const cJSON * const item); cJSON_IsNull(const cJSON * const item); cJSON_IsNumber(const cJSON * const item); cJSON_IsString(const cJSON * const item); cJSON_IsArray(const cJSON * const item); cJSON_IsObject(const cJSON * const item); cJSON_IsRaw(const cJSON * const item);
注意
创建cjson对象后,处理完需要进行内存释放:
如果是cjson里的对象,请使用cJSON_Delete()
如果不是对象:cJSON_free()或free()
零字符
cJSON不支持包含零字符' '或的字符串u0000。对于当前的API,这是不可能的,因为字符串以零结尾。
字符编码
cJSON仅支持UTF-8编码的输入。但是在大多数情况下,它不会拒绝无效的UTF-8作为输入,而只是将其原样传播。只要输入不包含无效的UTF-8,输出将始终是有效的UTF-8。
C标准
cJSON用ANSI C(或C89,C90)编写。如果您的编译器或C库未遵循此标准,则不能保证正确的行为。
注意:ANSI C不是C ++,因此不应使用C ++编译器进行编译。您可以使用C编译器对其进行编译,然后将其与C ++代码链接。尽管可以使用C ++编译器进行编译,但是不能保证正确的行为。
浮点数字
double除IEEE754双精度浮点数外,cJSON不正式支持任何实现。它可能仍然可以与其他实现一起使用,但是这些实现的错误将被视为无效。
目前,cJSON支持的浮点文字的最大长度为63个字符。
数组和对象的深层嵌套
cJSON不支持嵌套太深的数组和对象,因为这会导致堆栈溢出。为了防止这种CJSON_NESTING_LIMIT情况,默认情况下,cJSON将深度限制为1000,但是可以在编译时进行更改。
格式化输出
按标准的格式输出json字符串,输出完后一定要记得释放内存
代码
1 #include <stdio.h> 2 #include "cJSON.h" 3 #include "cJSON.c" 4 void main(){ 5 //待解析字符串 6 char *json_str="{"key1":"dongxiaodong","key2":1998,"key3":55778}"; 7 8 //输出原字符串 9 printf("原字符串:%s ",json_str); 10 11 //解析成json对象 12 cJSON * json_obj = cJSON_Parse(json_str); 13 14 //格式输出 15 char *json_print_str=NULL; 16 json_print_str=cJSON_Print(json_obj); 17 printf(" 输出内容: %s ",json_print_str); 18 19 //释放资源 20 free(json_print_str); 21 22 //释放资源 23 cJSON_Delete(json_obj); 24 }
json打包
cJSON_CreateObject函数可创建一个根数据项,在此之后就可以添加各种数据类型的子节点了,使用完成后需要通过cJSON_Delete()释放内存。
创建一层级的json
代码:
1 #include <stdio.h> 2 #include "cJSON.h" 3 #include "cJSON.c" 4 void main(){ 5 cJSON *root_obj = NULL;//根,json对象 6 char *out_str = NULL; //输出结果 7 root_obj =cJSON_CreateObject();//创建 8 //添加一个字符串,参数(根对象,键,值) 9 cJSON_AddStringToObject(root_obj, "key1", "dongxiaodong"); 10 //添加一个整型,参数(根对象,键,值) 11 cJSON_AddNumberToObject(root_obj, "key2",1998); 12 //添加一个浮点型,参数(根对象,键,值) 13 cJSON_AddNumberToObject(root_obj, "key3",22.33); 14 //添加一个bool类型,参数(根对象,键,值) 15 //bool值可以是0/1或false/true 16 cJSON_AddBoolToObject(root_obj, "key4",0); 17 //将json对象打包成字符串 18 out_str = cJSON_PrintUnformatted(root_obj); 19 //销毁json对象,释放内存 20 cJSON_Delete(root_obj); 21 //输出值:{"key1":"dongxiaodong","key2":1998,"key3":22.33,"key4":false} 22 printf("%s",out_str); 23 }
类型创建函数还有:
cJSON_AddNullToObject(cJSON * const object, const char * const name);
cJSON_AddTrueToObject(cJSON * const object, const char * const name);
cJSON_AddFalseToObject(cJSON * const object, const char * const name);
cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean);
cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);
cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);
cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw);
cJSON_AddObjectToObject(cJSON * const object, const char * const name);
cJSON_AddArrayToObject(cJSON * const object, const char * const name);
创建多层级的json
代码:
1 #include <stdio.h> 2 #include "cJSON.h" 3 #include "cJSON.c" 4 void main(){ 5 cJSON *root_obj = NULL;//根,json对象 6 cJSON *item_obj = NULL;//二级json对象 7 char *out_str = NULL; //输出结果 8 9 root_obj =cJSON_CreateObject();//创建 10 //添加一个字符串,参数(根对象,键,值) 11 cJSON_AddStringToObject(root_obj, "key1", "dongxiaodong"); 12 //添加一个整型,参数(根对象,键,值) 13 cJSON_AddNumberToObject(root_obj, "key2",1998); 14 15 //创建一个子json对象 16 item_obj= cJSON_AddObjectToObject(root_obj,"myson"); 17 //向孩子对象中添加内容 18 cJSON_AddStringToObject(item_obj, "sonkey1", "东小东"); 19 cJSON_AddNumberToObject(item_obj, "sonkey2",2020); 20 21 //将json对象打包成字符串 22 out_str = cJSON_PrintUnformatted(root_obj); 23 //销毁json对象,释放内存 24 cJSON_Delete(root_obj); 25 //输出值:{"key1":"dongxiaodong","key2":1998,"myson":{"sonkey1":"东小东","sonkey2":2020}} 26 printf("%s",out_str); 27 }
创建多层json(数组形式)
代码
1 #include <stdio.h> 2 #include "cJSON.h" 3 #include "cJSON.c" 4 void main(){ 5 cJSON *root_obj = NULL;//根,json对象 6 cJSON *item_obj = NULL;//数组对象 7 char *out_str = NULL; //输出结果 8 9 root_obj =cJSON_CreateObject();//创建 10 //添加一个字符串,参数(根对象,键,值) 11 cJSON_AddStringToObject(root_obj, "key1", "dongxiaodong"); 12 //添加一个整型,参数(根对象,键,值) 13 cJSON_AddNumberToObject(root_obj, "key2",1998); 14 15 //创建一个子数组对象 16 item_obj= cJSON_AddArrayToObject(root_obj,"myson"); 17 //向数组对象中添加内容 18 cJSON_AddItemToArray(item_obj,cJSON_CreateTrue()); 19 cJSON_AddItemToArray(item_obj,cJSON_CreateNumber(22)); 20 21 //将json对象打包成字符串 22 out_str = cJSON_PrintUnformatted(root_obj); 23 //销毁json对象,释放内存 24 cJSON_Delete(root_obj); 25 //输出值:{"key1":"dongxiaodong","key2":1998,"myson":[true,22]} 26 printf("%s",out_str); 27 }
创建的对象还可以是下面这些
cJSON_CreateNull(void);
cJSON_CreateTrue(void);
cJSON_CreateFalse(void);
cJSON_CreateBool(cJSON_bool boolean);
cJSON_CreateNumber(double num);
cJSON_CreateString(const char *string);
cJSON_CreateRaw(const char *raw);
cJSON_CreateArray(void);
cJSON_CreateObject(void);
创建混合json
代码
1 #include <stdio.h> 2 #include "cJSON.h" 3 #include "cJSON.c" 4 void main(){ 5 cJSON *root_obj = NULL;//根,json对象 6 cJSON *son_obj=NULL; 7 cJSON *item_obj = NULL;//数组对象 8 char *out_str = NULL; //输出结果 9 10 //根对象 11 root_obj =cJSON_CreateObject();//创建 12 //添加一个字符串,参数(根对象,键,值) 13 cJSON_AddStringToObject(root_obj, "key1", "dongxiaodong"); 14 //添加一个整型,参数(根对象,键,值) 15 cJSON_AddNumberToObject(root_obj, "key2",1998); 16 17 //创建一个子数组对象 18 item_obj= cJSON_AddArrayToObject(root_obj,"myson"); 19 //向数组对象中添加内容 20 cJSON_AddItemToArray(item_obj,cJSON_CreateTrue()); 21 cJSON_AddItemToArray(item_obj,cJSON_CreateNumber(22)); 22 23 //子对象 24 son_obj =cJSON_CreateObject();//创建 25 //添加一个字符串,参数(根对象,键,值) 26 cJSON_AddStringToObject(son_obj, "son1", "dongxiaodong"); 27 //添加一个整型,参数(根对象,键,值) 28 cJSON_AddNumberToObject(son_obj, "son2",1998); 29 cJSON_AddItemToArray(item_obj,son_obj); 30 31 //将json对象打包成字符串 32 out_str = cJSON_PrintUnformatted(root_obj); 33 //销毁json对象,释放内存 34 cJSON_Delete(root_obj); 35 //输出值:{"key1":"dongxiaodong","key2":1998,"myson":[true,22,{"son1":"dongxiaodong","son2":1998}]} 36 printf("%s",out_str); 37 }
json解析
解析一层级的json
代码:
1 #include <stdio.h> 2 #include "cJSON.h" 3 #include "cJSON.c" 4 void main(){ 5 //待解析字符串 6 char *json_str="{"key1":"dongxiaodong","key2":1998,"key3":22.33,"key4":true}"; 7 //解析成json对象 8 cJSON * json_obj = cJSON_Parse(json_str); 9 10 //项存储 11 cJSON *item=NULL; 12 13 //输出原字符串 14 printf("原字符串:%s ",json_str); 15 16 //获取string类型 17 item=cJSON_GetObjectItem(json_obj,"key1"); 18 printf(" key1:%s ",item->valuestring); 19 cJSON_Delete(item);//释放资源 20 21 //获取数字 22 item=cJSON_GetObjectItem(json_obj,"key2"); 23 printf(" key2:%d ",item->valueint); 24 cJSON_Delete(item);//释放资源 25 26 //获取数字 27 item=cJSON_GetObjectItem(json_obj,"key3"); 28 printf(" key3:%f ",item->valuedouble); 29 cJSON_Delete(item);//释放资源 30 31 //获取bool 32 item=cJSON_GetObjectItem(json_obj,"key4"); 33 printf(" key4:%d ",item->valueint); 34 cJSON_Delete(item);//释放资源 35 36 //是否资源 37 cJSON_Delete(json_obj); 38 }
解析多层级的json
代码
1 #include <stdio.h> 2 #include "cJSON.h" 3 #include "cJSON.c" 4 void main(){ 5 //待解析字符串 6 char *json_str="{"key1":"dongxiaodong","key2":1998,"myson":{"sonkey1":"东小东","sonkey2":2020}}"; 7 //解析成json对象 8 cJSON * json_obj = cJSON_Parse(json_str); 9 10 //项存储 11 cJSON *item=NULL; 12 //内部项存储 13 cJSON * item_item=NULL; 14 15 //输出原字符串 16 printf("原字符串:%s ",json_str); 17 18 //获取string类型 19 item=cJSON_GetObjectItem(json_obj,"key1"); 20 printf(" key1:%s ",item->valuestring); 21 cJSON_Delete(item);//释放资源 22 23 //获取数字 24 item=cJSON_GetObjectItem(json_obj,"key2"); 25 printf(" key2:%d ",item->valueint); 26 cJSON_Delete(item);//释放资源 27 28 //子串 29 item=cJSON_GetObjectItem(json_obj,"myson"); 30 item_item=cJSON_GetObjectItem(item,"sonkey1"); 31 printf(" myson(sonkey1):%s ",item_item->valuestring); 32 cJSON_Delete(item_item);//释放资源 33 34 item_item=cJSON_GetObjectItem(item,"sonkey2"); 35 printf(" myson(sonkey2):%d ",item_item->valueint); 36 cJSON_Delete(item_item);//释放资源 37 38 cJSON_Delete(item);//释放资源 39 40 //释放资源 41 cJSON_Delete(json_obj); 42 }
解析多层json(数组形式)
代码
1 #include <stdio.h> 2 #include "cJSON.h" 3 #include "cJSON.c" 4 void main(){ 5 //待解析字符串 6 char *json_str="{"key1":"dongxiaodong","key2":1998,"myson":[true,113]}"; 7 //解析成json对象 8 cJSON * json_obj = cJSON_Parse(json_str); 9 10 //项存储 11 cJSON *item=NULL; 12 //内部项存储 13 cJSON * item_item=NULL; 14 15 //输出原字符串 16 printf("原字符串:%s ",json_str); 17 18 //获取string类型 19 item=cJSON_GetObjectItem(json_obj,"key1"); 20 printf(" key1:%s ",item->valuestring); 21 cJSON_Delete(item);//释放资源 22 23 //获取数字 24 item=cJSON_GetObjectItem(json_obj,"key2"); 25 printf(" key2:%d ",item->valueint); 26 cJSON_Delete(item);//释放资源 27 28 //获取子串 29 item=cJSON_GetObjectItem(json_obj,"myson"); 30 31 //输出数组大小 32 printf(" 数组大小:%d ",cJSON_GetArraySize(item)); 33 34 //输出项1内容 35 item_item=cJSON_GetArrayItem(item,0); 36 printf(" myson(0):%d ",item_item->valueint); 37 //cJSON_Delete(item_item);//释放资源 38 39 //输出项2内容 40 item_item=cJSON_GetArrayItem(item,1); 41 printf(" myson(1):%d ",item_item->valueint); 42 cJSON_Delete(item_item);//释放资源 43 44 cJSON_Delete(item);//释放资源 45 46 //释放资源 47 cJSON_Delete(json_obj); 48 }
解析混合json
代码
1 #include <stdio.h> 2 #include "cJSON.h" 3 #include "cJSON.c" 4 void main(){ 5 //待解析字符串 6 char *json_str="{"key1":"dongxiaodong","key2":1998,"myson":[true,22,{"son1":"dongxiaodong","son2":1998}]}"; 7 //解析成json对象 8 cJSON * json_obj = cJSON_Parse(json_str); 9 10 //项存储 11 cJSON *item=NULL; 12 //内部项存储 13 cJSON * item_item=NULL; 14 15 //输出原字符串 16 printf("原字符串:%s ",json_str); 17 18 //获取string类型 19 item=cJSON_GetObjectItem(json_obj,"key1"); 20 printf(" key1:%s ",item->valuestring); 21 cJSON_Delete(item);//释放资源 22 23 //获取数字 24 item=cJSON_GetObjectItem(json_obj,"key2"); 25 printf(" key2:%d ",item->valueint); 26 cJSON_Delete(item);//释放资源 27 28 //获取子串 29 item=cJSON_GetObjectItem(json_obj,"myson"); 30 31 //输出数组大小 32 printf(" 数组大小:%d ",cJSON_GetArraySize(item)); 33 34 //输出项1内容 35 item_item=cJSON_GetArrayItem(item,0); 36 printf(" myson(0):%d ",item_item->valueint); 37 //cJSON_Delete(item_item);//释放资源 38 39 //输出项2内容 40 item_item=cJSON_GetArrayItem(item,1); 41 printf(" myson(1):%d ",item_item->valueint); 42 cJSON_Delete(item_item);//释放资源 43 44 //项3内容 45 item_item=cJSON_GetArrayItem(item,2); 46 cJSON *item_item_son=NULL; 47 48 item_item_son =cJSON_GetObjectItem(item_item,"son1"); 49 printf(" myson(2)(son1):%s ",item_item_son->valuestring); 50 cJSON_Delete(item_item_son);//释放资源 51 52 item_item_son =cJSON_GetObjectItem(item_item,"son2"); 53 printf(" myson(2)(son2):%d ",item_item_son->valueint); 54 cJSON_Delete(item_item_son);//释放资源 55 cJSON_Delete(item_item);//释放资源 56 57 cJSON_Delete(item);//释放资源 58 59 //释放资源 60 cJSON_Delete(json_obj); 61 }
附件:
cJSON.h
1 /* 2 Copyright (c) 2009-2017 Dave Gamble and cJSON contributors 3 4 Permission is hereby granted, free of charge, to any person obtaining a copy 5 of this software and associated documentation files (the "Software"), to deal 6 in the Software without restriction, including without limitation the rights 7 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 copies of the Software, and to permit persons to whom the Software is 9 furnished to do so, subject to the following conditions: 10 11 The above copyright notice and this permission notice shall be included in 12 all copies or substantial portions of the Software. 13 14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 THE SOFTWARE. 21 */ 22 23 #ifndef cJSON__h 24 #define cJSON__h 25 26 #ifdef __cplusplus 27 extern "C" 28 { 29 #endif 30 31 #if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32)) 32 #define __WINDOWS__ 33 #endif 34 35 #ifdef __WINDOWS__ 36 37 /* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options: 38 39 CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols 40 CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default) 41 CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol 42 43 For *nix builds that support visibility attribute, you can define similar behavior by 44 45 setting default visibility to hidden by adding 46 -fvisibility=hidden (for gcc) 47 or 48 -xldscope=hidden (for sun cc) 49 to CFLAGS 50 51 then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does 52 53 */ 54 55 #define CJSON_CDECL __cdecl 56 #define CJSON_STDCALL __stdcall 57 58 /* export symbols by default, this is necessary for copy pasting the C and header file */ 59 #if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS) 60 #define CJSON_EXPORT_SYMBOLS 61 #endif 62 63 #if defined(CJSON_HIDE_SYMBOLS) 64 #define CJSON_PUBLIC(type) type CJSON_STDCALL 65 #elif defined(CJSON_EXPORT_SYMBOLS) 66 #define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL 67 #elif defined(CJSON_IMPORT_SYMBOLS) 68 #define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL 69 #endif 70 #else /* !__WINDOWS__ */ 71 #define CJSON_CDECL 72 #define CJSON_STDCALL 73 74 #if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY) 75 #define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type 76 #else 77 #define CJSON_PUBLIC(type) type 78 #endif 79 #endif 80 81 /* project version */ 82 #define CJSON_VERSION_MAJOR 1 83 #define CJSON_VERSION_MINOR 7 84 #define CJSON_VERSION_PATCH 13 85 86 #include <stddef.h> 87 88 /* cJSON Types: */ 89 #define cJSON_Invalid (0) 90 #define cJSON_False (1 << 0) 91 #define cJSON_True (1 << 1) 92 #define cJSON_NULL (1 << 2) 93 #define cJSON_Number (1 << 3) 94 #define cJSON_String (1 << 4) 95 #define cJSON_Array (1 << 5) 96 #define cJSON_Object (1 << 6) 97 #define cJSON_Raw (1 << 7) /* raw json */ 98 99 #define cJSON_IsReference 256 100 #define cJSON_StringIsConst 512 101 102 /* The cJSON structure: */ 103 typedef struct cJSON 104 { 105 /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ 106 struct cJSON *next; 107 struct cJSON *prev; 108 /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ 109 struct cJSON *child; 110 111 /* The type of the item, as above. */ 112 int type; 113 114 /* The item's string, if type==cJSON_String and type == cJSON_Raw */ 115 char *valuestring; 116 /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ 117 int valueint; 118 /* The item's number, if type==cJSON_Number */ 119 double valuedouble; 120 121 /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ 122 char *string; 123 } cJSON; 124 125 typedef struct cJSON_Hooks 126 { 127 /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */ 128 void *(CJSON_CDECL *malloc_fn)(size_t sz); 129 void (CJSON_CDECL *free_fn)(void *ptr); 130 } cJSON_Hooks; 131 132 typedef int cJSON_bool; 133 134 /* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. 135 * This is to prevent stack overflows. */ 136 #ifndef CJSON_NESTING_LIMIT 137 #define CJSON_NESTING_LIMIT 1000 138 #endif 139 140 /* returns the version of cJSON as a string */ 141 CJSON_PUBLIC(const char*) cJSON_Version(void); 142 143 /* Supply malloc, realloc and free functions to cJSON */ 144 CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks); 145 146 /* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */ 147 /* Supply a block of JSON, and this returns a cJSON object you can interrogate. */ 148 CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); 149 CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length); 150 /* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ 151 /* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */ 152 CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); 153 CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated); 154 155 /* Render a cJSON entity to text for transfer/storage. */ 156 CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); 157 /* Render a cJSON entity to text for transfer/storage without any formatting. */ 158 CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); 159 /* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ 160 CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); 161 /* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ 162 /* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */ 163 CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format); 164 /* Delete a cJSON entity and all subentities. */ 165 CJSON_PUBLIC(void) cJSON_Delete(cJSON *item); 166 167 /* Returns the number of items in an array (or object). */ 168 CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); 169 /* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ 170 CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); 171 /* Get item "string" from object. Case insensitive. */ 172 CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string); 173 CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string); 174 CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string); 175 /* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ 176 CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void); 177 178 /* Check item type and return its value */ 179 CJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item); 180 CJSON_PUBLIC(double) cJSON_GetNumberValue(cJSON *item); 181 182 /* These functions check the type of an item */ 183 CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item); 184 CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item); 185 CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item); 186 CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item); 187 CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item); 188 CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item); 189 CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item); 190 CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item); 191 CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item); 192 CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item); 193 194 /* These calls create a cJSON item of the appropriate type. */ 195 CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void); 196 CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void); 197 CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void); 198 CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean); 199 CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num); 200 CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string); 201 /* raw json */ 202 CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw); 203 CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void); 204 CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void); 205 206 /* Create a string where valuestring references a string so 207 * it will not be freed by cJSON_Delete */ 208 CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string); 209 /* Create an object/array that only references it's elements so 210 * they will not be freed by cJSON_Delete */ 211 CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child); 212 CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child); 213 214 /* These utilities create an Array of count items. 215 * The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/ 216 CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count); 217 CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count); 218 CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count); 219 CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count); 220 221 /* Append item to the specified array/object. */ 222 CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item); 223 CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); 224 /* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object. 225 * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before 226 * writing to `item->string` */ 227 CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); 228 /* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ 229 CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); 230 CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); 231 232 /* Remove/Detach items from Arrays/Objects. */ 233 CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item); 234 CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which); 235 CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which); 236 CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string); 237 CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); 238 CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string); 239 CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); 240 241 /* Update array items. */ 242 CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */ 243 CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement); 244 CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); 245 CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); 246 CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem); 247 248 /* Duplicate a cJSON item */ 249 CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); 250 /* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will 251 * need to be released. With recurse!=0, it will duplicate any children connected to the item. 252 * The item->next and ->prev pointers are always zero on return from Duplicate. */ 253 /* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal. 254 * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */ 255 CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive); 256 257 /* Minify a strings, remove blank characters(such as ' ', ' ', ' ', ' ') from strings. 258 * The input pointer json cannot point to a read-only address area, such as a string constant, 259 * but should point to a readable and writable adress area. */ 260 CJSON_PUBLIC(void) cJSON_Minify(char *json); 261 262 /* Helper functions for creating and adding items to an object at the same time. 263 * They return the added item or NULL on failure. */ 264 CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name); 265 CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name); 266 CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name); 267 CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean); 268 CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); 269 CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string); 270 CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw); 271 CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name); 272 CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name); 273 274 /* When assigning an integer value, it needs to be propagated to valuedouble too. */ 275 #define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) 276 /* helper for the cJSON_SetNumberValue macro */ 277 CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); 278 #define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) 279 /* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */ 280 CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring); 281 282 /* Macro for iterating over an array or object */ 283 #define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next) 284 285 /* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */ 286 CJSON_PUBLIC(void *) cJSON_malloc(size_t size); 287 CJSON_PUBLIC(void) cJSON_free(void *object); 288 289 #ifdef __cplusplus 290 } 291 #endif 292 293 #endif
cJSON.c
1 /* 2 Copyright (c) 2009-2017 Dave Gamble and cJSON contributors 3 4 Permission is hereby granted, free of charge, to any person obtaining a copy 5 of this software and associated documentation files (the "Software"), to deal 6 in the Software without restriction, including without limitation the rights 7 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 copies of the Software, and to permit persons to whom the Software is 9 furnished to do so, subject to the following conditions: 10 11 The above copyright notice and this permission notice shall be included in 12 all copies or substantial portions of the Software. 13 14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 THE SOFTWARE. 21 */ 22 23 /* cJSON */ 24 /* JSON parser in C. */ 25 26 /* disable warnings about old C89 functions in MSVC */ 27 #if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) 28 #define _CRT_SECURE_NO_DEPRECATE 29 #endif 30 31 #ifdef __GNUC__ 32 #pragma GCC visibility push(default) 33 #endif 34 #if defined(_MSC_VER) 35 #pragma warning (push) 36 /* disable warning about single line comments in system headers */ 37 #pragma warning (disable : 4001) 38 #endif 39 40 #include <string.h> 41 #include <stdio.h> 42 #include <math.h> 43 #include <stdlib.h> 44 #include <limits.h> 45 #include <ctype.h> 46 #include <float.h> 47 48 #ifdef ENABLE_LOCALES 49 #include <locale.h> 50 #endif 51 52 #if defined(_MSC_VER) 53 #pragma warning (pop) 54 #endif 55 #ifdef __GNUC__ 56 #pragma GCC visibility pop 57 #endif 58 59 #include "cJSON.h" 60 61 /* define our own boolean type */ 62 #ifdef true 63 #undef true 64 #endif 65 #define true ((cJSON_bool)1) 66 67 #ifdef false 68 #undef false 69 #endif 70 #define false ((cJSON_bool)0) 71 72 /* define isnan and isinf for ANSI C, if in C99 or above, isnan and isinf has been defined in math.h */ 73 #ifndef isinf 74 #define isinf(d) (isnan((d - d)) && !isnan(d)) 75 #endif 76 #ifndef isnan 77 #define isnan(d) (d != d) 78 #endif 79 80 #ifndef NAN 81 #define NAN 0.0/0.0 82 #endif 83 84 typedef struct { 85 const unsigned char *json; 86 size_t position; 87 } error; 88 static error global_error = { NULL, 0 }; 89 90 CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void) 91 { 92 return (const char*) (global_error.json + global_error.position); 93 } 94 95 CJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item) 96 { 97 if (!cJSON_IsString(item)) 98 { 99 return NULL; 100 } 101 102 return item->valuestring; 103 } 104 105 CJSON_PUBLIC(double) cJSON_GetNumberValue(cJSON *item) 106 { 107 if (!cJSON_IsNumber(item)) 108 { 109 return NAN; 110 } 111 112 return item->valuedouble; 113 } 114 115 /* This is a safeguard to prevent copy-pasters from using incompatible C and header files */ 116 #if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 13) 117 #error cJSON.h and cJSON.c have different versions. Make sure that both have the same. 118 #endif 119 120 CJSON_PUBLIC(const char*) cJSON_Version(void) 121 { 122 static char version[15]; 123 sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); 124 125 return version; 126 } 127 128 /* Case insensitive string comparison, doesn't consider two NULL pointers equal though */ 129 static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2) 130 { 131 if ((string1 == NULL) || (string2 == NULL)) 132 { 133 return 1; 134 } 135 136 if (string1 == string2) 137 { 138 return 0; 139 } 140 141 for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++) 142 { 143 if (*string1 == '