Completion of error handling
Yeah, it might make sense to catch a NULL from cJSON_strdup, although this sadly won't enable any error handling from the external API since these are void functions.
How do you think about to adjust the return type for affected functions?
I have add some code to retrieve line number when error occur, whether syntax error in JSON or name/value is invalid for us.
demo1:
$cat -n demo2.json
1 {
2 "name": "Awesome 4K",
3 "resolutions": [
4 {
5 "width": 1280; # ';' should be ','
6 "height": 720
7 },
$./parser2 demo2.json
parse error: line: 5, content: ;
"height": 720
demo2:
$cat -n demo4.json
1 {
2 "name": "Awesome 4K",
3 "resolutions": [
4 {
5 "width": "what?", # width's value should be integer
6 "height": 720
7 },
$./parser2 ./demo4.json
"name": "Awesome 4K"
resolutions:
invalid "width" value: object: width, line: 5
- my cJSON fork: https://github.com/zzqcn/cJSON/tree/error-line
- sample: https://github.com/zzqcn/storage/tree/master/code/c/cjson
- doc(Chinese): https://www.yuque.com/zzqcn/ftvl2p/wu0kb5
Error handling makes sense, I like the demo1, when the input string is an invalid json string, the parse function should tell us where the problem is.
But I can't agree with demo2, we can't judge whether a field is string or number based on the field name. The value of "width" could be "100mm" while the "height"'s value is "2m" in some specific scenarios.
Hi @zzqcn , will you submit a PR?
@Alanscut I'm not sure it's userful to everyone, maybe you can review my code and make a desision.
@zzqcn I think your getErrorMsg function is a great addition. The only issue I have with cJSON at the moment is the lack of helpful error message when there is a syntax error in the file. A simple line number and a print of the line in which the error occurred is perfect! Please send in a Pull Request as @Alanscut said, I'd like to make use of this.
Also as @Alanscut points out, the functionality in your demo1 is useful since a json file is either syntactically correct or not, but the functionality in demo2 should not be included. That's up to the end user to decide what particular type an entry should be and handle it for their own use case.