# json **Repository Path**: Lamdonn/json ## Basic Information - **Project Name**: json - **Description**: C语言json解释器,简洁高效,灵活安全 - **Primary Language**: C - **License**: GPL-3.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 5 - **Forks**: 2 - **Created**: 2023-02-03 - **Last Updated**: 2025-06-30 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # json ## Introduction C language json interpreter. Including json text file parsing and generation, it occupies a small space, is safe and efficient, concise and flexible, and can be ported to most C language platforms with no difference or minor modifications. ## Example of use ### generate **test code** ```c void test_dump(void) { json_t json, t; /* create root node */ json = json_create_object(NULL); /* Add to root node */ json_add_string_to_object(json, "name", "json parser"); json_add_string_to_object(json, "version", "1.6.0"); json_add_string_to_object(json, "description", "This is a C language version of json streamlined parser."); json_add_string_to_object(json, "repository", "https://gitee.com/Lamdonn/json"); /* Add an empty array to the root node */ t = json_add_array_to_object(json, "keywords"); /* t receive added array */ json_add_string_to_array(t, "json"); json_add_string_to_array(t, "streamlined"); json_add_string_to_array(t, "parser"); /* Add an empty object to the root node */ t = json_add_object_to_object(json, "others"); /* t receive added object */ json_add_bool_to_object(t, "open", JSON_TRUE); json_add_string_to_object(t, "license", "GPL3.0"); /* Dump JSON objects to a file */ json_file_dump(json, "test.json"); /* Delete after end of use */ json_delete(json); } ``` Build file name: **test.json** ```json { "name": "json parser", "version": "1.6.0", "description": "This is a C language version of json streamlined parser.", "repository": "https://gitee.com/Lamdonn/json", "keywords": ["json", "streamlined", "parser"], "others": { "open": true, "license": "GPL3.0" } } ``` ### Parse Parse the previously generated file: **test.json** **test code** ```c void test_load(void) { json_t json, t; /* Load json file */ json = json_file_load("test.json"); if (!json) return; t = json_to_key(json, "name"); if (json_isstring(t)) printf("module name: %s\r\n", json_value_string(t)); t = json_to_key(json, "others", "open"); if (json_isbool(t)) printf("open: %s\r\n", json_value_bool(t) ? "yes" : "no"); t = json_to_index(json, 4, 1); if (json_isstring(t)) printf("keywords[1]: %s\r\n", json_value_string(t)); /* Delete after end of use */ json_delete(json); } ``` **print result** ``` module name: json parser open: yes keywords[1]: streamlined ``` ## json syntax json syntax is a subset of **JavaScript** object representation syntax. 1. The data is in the `key-value pair`, and the key value is indicated by `:` 2. The data is separated by comma `,` 3. Use the slash `\` to escape characters 4. Brackets `[]` save the array, and the array can contain multiple values of different types 5. Braces `{}` save the object, and the object can contain multiple key-value pairs ### json data type ```c #define JSON_TYPE_NULL (1) /* base type, null */ #define JSON_TYPE_BOOL (2) /* base type, bool */ #define JSON_TYPE_NUMBER (3) /* base type, number */ #define JSON_TYPE_STRING (4) /* base type, string */ #define JSON_TYPE_ARRAY (5) /* extension type, array */ #define JSON_TYPE_OBJECT (6) /* extension type, object */ ``` ### json key-value pair Key-value pair writing sample: ```json "key" : "value" ``` The type of the key is a string type and needs to be enclosed in double quotes `""`. And the value can be any of the following basic types. * Empty type (`null`) * Boolean type (`true`, `false`) * Number type (integer or float) * String type (in double quotes `""`) * Array type (in square brackets `[]`) * Object type (in braces `{}`) ### grammar example ```json { "information": { "module": "json", "history": [1.0, 1.1, 1.2, 1.21, 1.3, 1.31, 1.32, 1.42], "paser": true, "print": false }, "other": null } ``` ## API ### class structure ```c /* json define */ typedef struct _JSON_ { /* link */ struct _JSON_* next; /* protected, not readable and writable */ /* information */ int info; /* protected, readable only */ /* The space behind the structure is variable key and value */ /* [char *key] */ /* [int value / double value / char* value / json_t child] */ } JSON, *json_t; ``` In json syntax, data is stored in the form of key-value pairs (when stored in an array, there is no key). In this json parser, the smallest unit of storage and the only storage unit is the **JSON** structure indicated above, and this structure contains a total of 4 members, *next pointer, info, *key ( Implicit members), value (implicit members), the key-value pairs are implicit members, because not all JSON objects need keys (such as array objects), and the value is not a member of a fixed type, and the type can be based on `info` information is configured as int, double, *char and other types. Using this implicit structure member method can greatly save space. #### *next member The JSON structure is the only storage unit, which is stored and maintained in the form of a one-way linked list on the storage structure. ``` { "name": "json parser", next ( "version": "1.6.0", next ( "description": "This is a C language version of json streamlined parser.", next ( "repository": "https://gitee.com/Lamdonn/json", next ( "keywords": ["json", "streamlined", "parser"], next ( \__next__/ \__next__/ "others": { ... } } ``` #### info member ``` bits low --> high --------------------------------------------------------------------- | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | NA | NA | ....... --------------------------------------------------------------------- \______________________________/ | | | low 8bits | | | | | | | V | | | #define JSON_TYPE_UNKNOW (0) | | | #define JSON_TYPE_NULL (1) | | | #define JSON_TYPE_BOOL (2) | | +----> JSON_WITH_KEY (1<<10) #define JSON_TYPE_NUMBER (3) | | #define JSON_TYPE_STRING (4) | +--------> JSON_NUMBER_INT (1<<9) #define JSON_TYPE_ARRAY (5) | #define JSON_TYPE_OBJECT (6) +------------> JSON_VALUE_B_TRUE (1<<8) ``` The info member is int type, the lower eight bits store the basic type of json object (null, bool, number, string, array, object), and the ninth bit stores the value of bool type (effective when the basic type is bool type, 1 is true, 0 is false), the 10th bit stores the digital integer flag (when the basic type is digital, 1 is an integer, 0 is a floating point type), the 10th bit marks whether the json object has a key (1 is keyed, 0 is not keyed), and the remaining bits are reserved. The information of the info member will determine whether to create implicit parameters when creating a json object. For example, if the **JSON_WITH_KEY** bit is effective, reserve space for **char* key** when creating it, for example, according to different basic types Determine the type of the implicit parameter **value** (which one of int, double, char*, json_t, or no value). #### key member The key member is implicit and indeterminate. It depends on the actual storage type. The key is a string and does not have deduplication. That is, the same level of json objects can have the same key. Which key to access depends on In the way of searching, this json parser adopts the storage structure of a one-way linked list, and the access will access the first object with the same name. #### value member The value member is implicitly indeterminate. According to the basic type of info, it is determined to add the space required by the corresponding type at the end of the structure. For example, for integers, add **sizeof(int)** to store integer data. ### Common APIs #### json parsing method prototype ```c json_t json_loads(const char* text); // load text json_t json_file_load(char* filename); // load file ``` `json_loads` function passes in json text information, then it can return the parsed json object handle. The `json_file_load` function is to directly pass in the file name to load the file and return the json object. Inside the function, the file is read through the C language standard file operation function set, and then the `json_loads` function is applied for parsing, which supports utf8 encoded files. #### json generation method prototype ```c char* json_dumps(json_t json, int preset, int unformat, int* len); // generate text int json_file_dump(json_t json, char* filename); // generate file ``` The `json_dumps` function converts json objects into text information, where `preset` is the preset text length, and if the preset length is close to the final output text length, it can reduce the number of memory reallocations and improve conversion efficiency; `unformat` Whether to use formatted output, if not formatted, the text will be squeezed into one line; `len` is the output length of the conversion. The `json_file_dump` function applies the `json_dumps` function to store text information to a file with a specified name. #### json get child object method prototype ```c json_t json_get_child(json_t json, const char* key, int index); #define json_to_index(json, i, ...) #define json_to_key(json, key, ...) ``` In the json object, the key does not have duplicate checking, that is, in the same level of json, there may be multiple keys with the same name, and the `json_get_child` method can be used to match a specific key. This function, when `key` is passed in NULL, only the index will work, and the sub-object will be matched according to the index. When `key` is not NULL, only the sub-object of the corresponding key will be matched, and the index will be used to indicate Match the first few objects named `key`. ```c t = json_get_child(json, NULL, 3); // Find the child object with index 3 t = json_get_child(json, "a", 3); // Find the child object whose key is "a" and whose index is 3 ``` The two methods `json_to_index` and `json_to_key` can easily get sub-objects, and can be used as a search method to find out whether there is a corresponding sub-object. The `json_to_index` method obtains sub-objects by index, regardless of whether the object type is an array or an object, this method can be used. The `json_to_key` method obtains sub-objects by key, but this method is only applicable to objects of type object, because arrays do not have keys. The parameters of these two methods have indeterminate parameters, which can input several indexes or keys to continuously obtain the sub-objects of the next level. For example: ```c t = json_to_key(json, "information", "module", "name"); ``` equivalent ```c t = json_to_key(json, "information"); t = json_to_key(t, "module"); t = json_to_key(t, "name"); ``` #### json get the value type of the object method prototype ```c #define json_type(json) // get the type #define json_isnull(json) // determine whether it is an empty type #define json_isbool(json) // determine whether it is a Boolean type #define json_isnumber(json) // determine whether it is a number type #define json_isint(json) // determine whether it is a digital integer #define json_isfloat(json) // determine whether it is a digital floating point type #define json_isstring(json) // determine whether it is a string type #define json_isarray(json) // determine whether it is an array type #define json_isobject(json) // determine whether it is an object type ``` #### json get key and value of object method prototype ```c const char* json_key(json_t json); int json_value_bool(json_t json); int json_value_int(json_t json); double json_value_float(json_t json); const char* json_value_string(json_t json); json_t json_value_array(json_t json); json_t json_value_object(json_t json); ``` Before obtaining value-to-value operations, it is recommended to judge whether it is the expected type. If the operation is not of the correct type, the storage structure of json may be destroyed or even cause the program to crash. #### json create object method prototype ```c json_t json_create_null(char* key); json_t json_create_bool(char* key, int b); json_t json_create_int(char* key, int num); json_t json_create_float(char* key, double num); json_t json_create_string(char* key, const char* string); json_t json_create_object(char* key); json_t json_create_array(char* key); ``` This type of method can create the basic type of json, and arrays and objects can store json objects, so they are created as empty arrays and empty objects by default. Except for these two, other methods can specify initialization values ​​at the time of creation. The created object specifies `key`, if the key is passed in, the created object can be added to the object type, and if the key is passed in, the created object can be added to the array type. Arrays can store any type of data, but generally store the same type of data, so the creation method of the array provides an additional initialization method. ```c json_t json_create_array_int(char* key, const int* numbers, int count); json_t json_create_array_float(char* key, const float* numbers, int count); json_t json_create_array_double(char* key, const double* numbers, int count); json_t json_create_array_string(char* key, const char** strings, int count); ``` According to the C language array, initialize the data to the json array. #### json delete object method prototype ```c void json_delete(json_t json); ``` Deletes json itself and all expanded sub-objects. json needs to be independent, that is, it can only be the root node. #### json attach and detach object method prototype ```c json_t json_attach(json_t json, int index, json_t item); json_t json_detach(json_t json, char *key, int index); ``` The `json_attach` method is to attach the created object to another object according to the index, and the value type of the attached object must be an array type or an object type. Returns the item itself on success, or NULL on failure. The `json_detach` method is to detach the specified child object from the array or object according to the same `key` and `index` of `json_get_child`, and return its child object, or return NULL if it fails. These two methods do not involve the creation or deletion of objects, but only the adjustment of the storage structure, and the operation of adding or removing is realized by cooperating with other methods. As for the inserted index, in addition to inserting into the specified index, you can also specify the commonly used head insertion and tail insertion. ```c #define JSON_HEAD #define JSON_TAIL ``` #### json add object ```c #define json_add_null_to_array(json) #define json_add_bool_to_array(json, b) #define json_add_int_to_array(json, n) #define json_add_float_to_array(json, n) #define json_add_string_to_array(json, s) #define json_add_array_to_array(json) #define json_add_object_to_array(json) #define json_add_null_to_object(json, key) #define json_add_bool_to_object(json, key, b) #define json_add_int_to_object(json, key, n) #define json_add_float_to_object(json, key, n) #define json_add_string_to_object(json, key, s) #define json_add_array_to_object(json, key) #define json_add_object_to_object(json, key) ``` These methods are created through the cooperation of the creation method and the attach method to add specific types of data to the array or object-type json object. #### json erase child object ```c #define json_erase(json, key, index) #define json_erase_by_index(json, index) #define json_erase_by_key(json, key) ``` These methods are combined by the delete method and the detach method to erase specific sub-objects in the array or object. #### json object modification method prototype ```c int json_set_key(json_t json, const char* key); int json_set_bool(json_t json, int b); int json_set_int(json_t json, int num); int json_set_float(json_t json, double num); int json_set_string(json_t json, const char* string); ``` If the value type is not an array or an object, you can call the corresponding set method to modify it directly according to the current type. However, when the original type is inconsistent with the modified type, you need to call the replace method through its upper-level object to modify. #### json replace ```c json_t json_replace(json_t json, char *key, int index, json_t item); ``` This method is a fallback method when modifications cannot be made with the set method. Through the parent, match the child object, and replace the matched child object with the new object. #### json object deep copy method prototype ```c json_t json_duplicate(json_t json); ``` Deep copy a json object based on the source json object. #### json configuration memory hook function method prototype ```c typedef void* (*malloc_t)(size_t size); typedef void (*free_t)(void* block); typedef void* (*realloc_t)(void* block, size_t size); int json_set_hooks(malloc_t _malloc, free_t _free, realloc_t _realloc); ``` C language is widely used in embedded applications. For different embedded platforms, memory allocation and release functions have the same interface. This method can set corresponding memory hook functions according to different platforms. Standard allocation and release functions have been used by default. `json_set_hooks` must specify matching `malloc` and `free`, if `realloc` is not available, you can not specify it (json built-in simulates `realloc` through `malloc` and `free`), otherwise the setting fails. #### json parsing error method prototype ```c int json_error_info(int* line, int* column); ``` This json parser has a more accurate error reporting mechanism. When executing the `json_loads` class loading function, if a null value is returned to indicate that the parsing error is wrong, you can call the `json_error_info` method to view the specific error information. The `json_file_load` function has already output an error information. Among the parameters, `*line` is the output error line; `*column` is the output error column, and the return value is the error type. In the following example, there is an error with a minus sign in front of `true`. ```json { "name": "json parser", "version": "1.6.0", "description": "This is a C language version of json streamlined parser.", "repository": "https://gitee.com/Lamdonn/json", "keywords": ["json", "streamlined", "parser"], "others": { "open": -true, "license": "GPL3.0" } } ``` When loading this file, an error occurs, indicating that an error with error code 7 appears near 'true' in line 8 and column 12. ``` Parsing error, code 7 line 8 column 12, near [true]. ``` Error types include the following. ```c #define JSON_E_OK (0) // ok #define JSON_E_INVALID (1) // invalid #define JSON_E_GRAMMAR (2) // common grammatical error #define JSON_E_END (3) // extra invalid text at the end of the text #define JSON_E_KEY (4) // an error occurred while parsing key #define JSON_E_VALUE (5) // an error occurred while parsing value #define JSON_E_MEMORY (6) // memory allocation failed #define JSON_E_NUMBER (7) // invalid number #define JSON_E_INDICATOR (8) // missing indicator ':' ``` ## contact author Email: Lamdonn@163.com