cJSON_CreateObject
cJSON_CreateObject
If you are working with JSON data in C, you might come across the need to create a new JSON object. This is where the cJSON_CreateObject
function comes in handy.
The cJSON_CreateObject
function is part of the cJSON library, which is a lightweight and portable JSON parser for C. This function creates a new JSON object and returns a pointer to it. Here's how you can use it:
cJSON *object = cJSON_CreateObject();
This will create a new JSON object and assign it to the object
pointer. You can then add key-value pairs to the object using the cJSON_AddItemToObject
function:
cJSON_AddItemToObject(object, "name", cJSON_CreateString("John"));
cJSON_AddItemToObject(object, "age", cJSON_CreateNumber(25));
This will add two key-value pairs to the JSON object: "name": "John" and "age": 25.
Alternatively, if you want to create a new JSON object with some initial key-value pairs, you can use the cJSON_CreateObject
function with a set of arguments:
cJSON *object = cJSON_CreateObject(
cJSON_CreateString("name"), cJSON_CreateString("John"),
cJSON_CreateString("age"), cJSON_CreateNumber(25),
NULL
);
This will create a new JSON object with the same two key-value pairs as before.
Overall, the cJSON_CreateObject
function is a useful tool for working with JSON data in C. It allows you to create new JSON objects and add key-value pairs to them with ease.