Reputation: 1125
I'm parsing a JSON string using "rapidjson". I'm studying following example of SAX type parsing of json object.
In this SAX type parsing rapidjson calls the event handler for each data type as received whiling parsing.(as documents at (https://github.com/miloyip/rapidjson/blob/2e0b3de8d68758b2866fff5f047c893b8a1c4290/doc/sax.md)
How I can differentiate that given element is key and value corresponding to that key?
Upvotes: 2
Views: 1522
Reputation: 5072
You can only differentiate the keys and values by the order of event sequence.
When the Reader
(SAX Parser) encounters an JSON object, it calls StartObject()
of the handler. Then there will be a sequence of key-value pairs. The key must be a String()
call, but the value can be any JSON value types. And finally it calls EndObject()
.
So, you need to keep track of the state of the parsing. For simple structure, it just need a an enum to represent the current state. For recursive structure, you may need a custom stack.
In this section, it shows an example of parsing a simple object into a custom data structure. And it needs to handle 3 states. Or, you may use a counter for number of calls to String()
and uses odd/even to determine whether it is key or value.
Using SAX API may be more difficult sometimes. On the other hand, it provides better performance and less memory overheads.
Update: 2014/9/5
A pull-request which adds a Key()
event in additional to String()
has been merged. The new interface shall simplify writing custom handlers.
Upvotes: 1