[json-c] Tutorial part 4: Parsing
Creating (writing lines for) new json_objects
is extremely boring. Moreover, if you have to handle json as a string in input making your own parser isn’t a bright idea.
Introducing json-c parser
To parse a json string in json-c you have two methods. The first one is very easy to use but don’t offer any options. The second one supports more options, but requires some extra work to get the job done.
I will only cover the first method because it’s the only one I used. However, the second method isn’t useless: It should be more efficient if you frequently parse a lot of json strings. Those slight performance improvements come from the implementation of the first method (roughly):
- create a
json_tokener
- try to parse the json string
- delete the tokener
Back to the first method now. Two sets of functions are available. Here are the prototypes:
The first function won’t display any errors. If the parsing succeeds you have the corresponding json_object
, otherwise you get NULL.
The second set of functions allows you to get a reason why the parsing failed - it might be of assistance in case of malformated json strings (on purpose? ).
Example
Pretty simple to use, right? So here is a short example:
And the output:
The End
I hope you have all the explanations you need to get started with json-c; if not, you can complain in the comments ;).