@@ -12,6 +12,7 @@ Ultralightweight JSON parser in ANSI C.
...
@@ -12,6 +12,7 @@ Ultralightweight JSON parser in ANSI C.
*[Working with the data structure](#working-with-the-data-structure)
*[Working with the data structure](#working-with-the-data-structure)
*[Parsing JSON](#parsing-json)
*[Parsing JSON](#parsing-json)
*[Printing JSON](#printing-json)
*[Printing JSON](#printing-json)
*[Example](#example)
*[Some JSON](#some-json)
*[Some JSON](#some-json)
*[Here's the structure](#heres-the-structure)
*[Here's the structure](#heres-the-structure)
*[Caveats](#caveats)
*[Caveats](#caveats)
...
@@ -252,6 +253,216 @@ If you have a rough idea of how big your resulting string will be, you can use `
...
@@ -252,6 +253,216 @@ If you have a rough idea of how big your resulting string will be, you can use `
These dynamic buffer allocations can be completely avoided by using `cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format)`. It takes a buffer to a pointer to print to and it's length. If the length is reached, printing will fail and it returns `0`. In case of success, `1` is returned. Note that you should provide 5 bytes more than is actually needed, because cJSON is not 100% accurate in estimating if the provided memory is enough.
These dynamic buffer allocations can be completely avoided by using `cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format)`. It takes a buffer to a pointer to print to and it's length. If the length is reached, printing will fail and it returns `0`. In case of success, `1` is returned. Note that you should provide 5 bytes more than is actually needed, because cJSON is not 100% accurate in estimating if the provided memory is enough.
### Example
In this example we want to build and parse the following JSON:
```json
{
"name":"Awesome 4K",
"resolutions":[
{
"width":1280,
"height":720
},
{
"width":1920,
"height":1080
},
{
"width":3840,
"height":2160
}
]
}
```
#### Printing
Let's build the above JSON and print it to a string:
```c
//create a monitor with a list of supported resolutions
char*create_monitor(void)
{
constunsignedintresolution_numbers[3][2]={
{1280,720},
{1920,1080},
{3840,2160}
};
char*string=NULL;
cJSON*name=NULL;
cJSON*resolutions=NULL;
cJSON*resolution=NULL;
cJSON*width=NULL;
cJSON*height=NULL;
size_tindex=0;
cJSON*monitor=cJSON_CreateObject();
if(monitor==NULL)
{
gotoend;
}
name=cJSON_CreateString("Awesome 4K");
if(name==NULL)
{
gotoend;
}
/* after creation was successful, immediately add it to the monitor,
* thereby transfering ownership of the pointer to it */
Note that there are no NULL checks except for the result of `cJSON_Parse` because `cJSON_GetObjectItemCaseSensitive` checks for `NULL` inputs already, so a `NULL` value is just propagated and `cJSON_IsNumber` and `cJSON_IsString` return `0` if the input is `NULL`.