cJSON
cJSON copied to clipboard
Why are all the results wrapped with ""
char* data = cJSON_Print(value); printf(data)
The print result is "2021-10-18"
What i expect is 2021-10-18
Because data's type is string, when it's key and value's type is also string, then we should enclose it with quotes. like this:
the original json structure: {"date": "2021-10-18"}
after print with cJSON_Print
, char * data = "{"date" : "2021-10-18"}"
so if you printf data
, the date of 2021-10-18
absolutely wrapped with quotes
I am afraid I dont think that's the case, such the example:
char date[11] = "2021-10-18"; printf(date);
The print result is 2021-10-18
not "2021-10-18"
but i printf("cJSON_Print date") result is "2021-10-18"
so i can not compare them
By the way, I am a java developer
the resulting print 2021-10-18
is still char*
not the number. you still not able to compare with numbers directly.
"2021-10-18"
just add character \"
at the beginning and the ending.
I am afraid I dont think that's the case, such the example:
char date[11] = "2021-10-18"; printf(date);
The print result is2021-10-18
not"2021-10-18"
but i printf("cJSON_Print date") result is"2021-10-18"
so i can not compare them By the way, I am a java developer
What cJSON_Print
is always in legal JSON syntax. 2021-10-18
without quotes is not legal JSON.
I am afraid I dont think that's the case, such the example:
char date[11] = "2021-10-18"; printf(date);
The print result is2021-10-18
not"2021-10-18"
Yes, this absolutely print 2021-10-18
.
But if char date[13] = "\"2021-10-18\""
, then print will be "2021-10-18"
but i printf("cJSON_Print date") result is
"2021-10-18"
so i can not compare them
At first, you can't pass date
which type is char* to cJSON_Print
, we must pass a cJSON item to it.
in RFC-8259, a valid simple json only contains value:
Here are three small JSON texts containing only values:
- "Hello world!" --> string, must be wrapped with quote: "2021-10-18"
- 42 --> number
- true --> boolean
so let's parse the date: cJSON* item = cJSON_Parse(date)
-
if
char* date = "2021-10-18"
, parsing fails, because now we pass a json text like2021-10-18
to the parser, It is neither a string nor a number. -
if
char* date = "2021"
, parsing success, item->type iscJSON_Number
thencJSON_Print(item)
will return a number2021
-
if
char* date = "\"2021-10-18\""
parsing success, item->type iscJSON_String
thencJSON_Print(item)
will return a string"2021-10-18"
, and usingprintf
print it, it will be"2021-10-18"
By the way, I am a java developer
let's explain the demo with fastjson
(version1.2.58, a java json lib)
public void test() {
String json = "\"2021-10-18\""; // if json = "2021-10-18", then parse will fail
Object obj = JSON.parse(json);
System.out.println(obj);
String str = JSON.toJSONString(obj); // equivalent to cJSON_Print in cJSON
System.out.println(str); // "2021-10-18", the same with cJSON
}