From d18279045a01d9c397dd47b323369b4b85107edf Mon Sep 17 00:00:00 2001 From: Weixie Cui Date: Mon, 16 Mar 2026 19:30:57 +0800 Subject: [PATCH] fix: set valueint for cJSON_CreateTrue and cJSON_CreateBool cJSON_CreateTrue() and cJSON_CreateBool(true) left valueint as 0, while parsing "true" from JSON sets valueint to 1. This inconsistency caused programmatically created boolean values to behave differently from parsed ones. --- cJSON.c | 2 ++ tests/misc_tests.c | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/cJSON.c b/cJSON.c index 88c2d95b..7979771c 100644 --- a/cJSON.c +++ b/cJSON.c @@ -2475,6 +2475,7 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void) if(item) { item->type = cJSON_True; + item->valueint = 1; } return item; @@ -2497,6 +2498,7 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean) if(item) { item->type = boolean ? cJSON_True : cJSON_False; + item->valueint = boolean ? 1 : 0; } return item; diff --git a/tests/misc_tests.c b/tests/misc_tests.c index fe2325e9..45272361 100644 --- a/tests/misc_tests.c +++ b/tests/misc_tests.c @@ -799,6 +799,27 @@ static void cjson_parse_big_numbers_should_not_report_error(void) cJSON_Delete(valid_big_number_json_object2); } +static void cjson_create_true_should_set_valueint(void) +{ + cJSON *parsed = cJSON_Parse("true"); + cJSON *created_true = cJSON_CreateTrue(); + cJSON *created_bool = cJSON_CreateBool(1); + cJSON *created_false = cJSON_CreateFalse(); + cJSON *created_bool_false = cJSON_CreateBool(0); + + TEST_ASSERT_EQUAL_INT(1, parsed->valueint); + TEST_ASSERT_EQUAL_INT(1, created_true->valueint); + TEST_ASSERT_EQUAL_INT(1, created_bool->valueint); + TEST_ASSERT_EQUAL_INT(0, created_false->valueint); + TEST_ASSERT_EQUAL_INT(0, created_bool_false->valueint); + + cJSON_Delete(parsed); + cJSON_Delete(created_true); + cJSON_Delete(created_bool); + cJSON_Delete(created_false); + cJSON_Delete(created_bool_false); +} + int CJSON_CDECL main(void) { UNITY_BEGIN(); @@ -833,6 +854,7 @@ int CJSON_CDECL main(void) RUN_TEST(cjson_set_valuestring_to_object_should_not_leak_memory); RUN_TEST(cjson_set_bool_value_must_not_break_objects); RUN_TEST(cjson_parse_big_numbers_should_not_report_error); + RUN_TEST(cjson_create_true_should_set_valueint); return UNITY_END(); }