DaveGamble / cJSON

Ultralightweight JSON parser in ANSI C
MIT License
10.68k stars 3.21k forks source link

Why are all the results wrapped with "" #619

Open hury88 opened 2 years ago

hury88 commented 2 years ago

char* data = cJSON_Print(value); printf(data)

The print result is "2021-10-18"

What i expect is 2021-10-18

Alanscut commented 2 years ago

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

hury88 commented 2 years ago

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

tarzan115 commented 2 years ago

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.

zhaozhixu commented 2 years ago

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

What cJSON_Print is always in legal JSON syntax. 2021-10-18 without quotes is not legal JSON.

Alanscut commented 2 years ago

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"

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)

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
}