简体   繁体   中英

How to differentiate between key and value while parsing JSON string using rapidjson?

I'm parsing a JSON string using "rapidjson". I'm studying following example of SAX type parsing of json object.

https://github.com/miloyip/rapidjson/blob/75cee948d44876f22f7215b9bd64733c3d7fee51/example/simplereader/simplereader.cpp

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM