]> git.proxmox.com Git - ceph.git/blob - ceph/src/rapidjson/doc/sax.md
update sources to v12.1.0
[ceph.git] / ceph / src / rapidjson / doc / sax.md
1 # SAX
2
3 The term "SAX" originated from [Simple API for XML](http://en.wikipedia.org/wiki/Simple_API_for_XML). We borrowed this term for JSON parsing and generation.
4
5 In RapidJSON, `Reader` (typedef of `GenericReader<...>`) is the SAX-style parser for JSON, and `Writer` (typedef of `GenericWriter<...>`) is the SAX-style generator for JSON.
6
7 [TOC]
8
9 # Reader {#Reader}
10
11 `Reader` parses a JSON from a stream. While it reads characters from the stream, it analyze the characters according to the syntax of JSON, and publish events to a handler.
12
13 For example, here is a JSON.
14
15 ~~~~~~~~~~js
16 {
17 "hello": "world",
18 "t": true ,
19 "f": false,
20 "n": null,
21 "i": 123,
22 "pi": 3.1416,
23 "a": [1, 2, 3, 4]
24 }
25 ~~~~~~~~~~
26
27 While a `Reader` parses this JSON, it publishes the following events to the handler sequentially:
28
29 ~~~~~~~~~~
30 StartObject()
31 Key("hello", 5, true)
32 String("world", 5, true)
33 Key("t", 1, true)
34 Bool(true)
35 Key("f", 1, true)
36 Bool(false)
37 Key("n", 1, true)
38 Null()
39 Key("i")
40 UInt(123)
41 Key("pi")
42 Double(3.1416)
43 Key("a")
44 StartArray()
45 Uint(1)
46 Uint(2)
47 Uint(3)
48 Uint(4)
49 EndArray(4)
50 EndObject(7)
51 ~~~~~~~~~~
52
53 These events can be easily matched with the JSON, except some event parameters need further explanation. Let's see the `simplereader` example which produces exactly the same output as above:
54
55 ~~~~~~~~~~cpp
56 #include "rapidjson/reader.h"
57 #include <iostream>
58
59 using namespace rapidjson;
60 using namespace std;
61
62 struct MyHandler : public BaseReaderHandler<UTF8<>, MyHandler> {
63 bool Null() { cout << "Null()" << endl; return true; }
64 bool Bool(bool b) { cout << "Bool(" << boolalpha << b << ")" << endl; return true; }
65 bool Int(int i) { cout << "Int(" << i << ")" << endl; return true; }
66 bool Uint(unsigned u) { cout << "Uint(" << u << ")" << endl; return true; }
67 bool Int64(int64_t i) { cout << "Int64(" << i << ")" << endl; return true; }
68 bool Uint64(uint64_t u) { cout << "Uint64(" << u << ")" << endl; return true; }
69 bool Double(double d) { cout << "Double(" << d << ")" << endl; return true; }
70 bool String(const char* str, SizeType length, bool copy) {
71 cout << "String(" << str << ", " << length << ", " << boolalpha << copy << ")" << endl;
72 return true;
73 }
74 bool StartObject() { cout << "StartObject()" << endl; return true; }
75 bool Key(const char* str, SizeType length, bool copy) {
76 cout << "Key(" << str << ", " << length << ", " << boolalpha << copy << ")" << endl;
77 return true;
78 }
79 bool EndObject(SizeType memberCount) { cout << "EndObject(" << memberCount << ")" << endl; return true; }
80 bool StartArray() { cout << "StartArray()" << endl; return true; }
81 bool EndArray(SizeType elementCount) { cout << "EndArray(" << elementCount << ")" << endl; return true; }
82 };
83
84 void main() {
85 const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } ";
86
87 MyHandler handler;
88 Reader reader;
89 StringStream ss(json);
90 reader.Parse(ss, handler);
91 }
92 ~~~~~~~~~~
93
94 Note that, RapidJSON uses template to statically bind the `Reader` type and the handler type, instead of using class with virtual functions. This paradigm can improve the performance by inlining functions.
95
96 ## Handler {#Handler}
97
98 As the previous example showed, user needs to implement a handler, which consumes the events (function calls) from `Reader`. The handler must contain the following member functions.
99
100 ~~~~~~~~~~cpp
101 class Handler {
102 bool Null();
103 bool Bool(bool b);
104 bool Int(int i);
105 bool Uint(unsigned i);
106 bool Int64(int64_t i);
107 bool Uint64(uint64_t i);
108 bool Double(double d);
109 bool RawNumber(const Ch* str, SizeType length, bool copy);
110 bool String(const Ch* str, SizeType length, bool copy);
111 bool StartObject();
112 bool Key(const Ch* str, SizeType length, bool copy);
113 bool EndObject(SizeType memberCount);
114 bool StartArray();
115 bool EndArray(SizeType elementCount);
116 };
117 ~~~~~~~~~~
118
119 `Null()` is called when the `Reader` encounters a JSON null value.
120
121 `Bool(bool)` is called when the `Reader` encounters a JSON true or false value.
122
123 When the `Reader` encounters a JSON number, it chooses a suitable C++ type mapping. And then it calls *one* function out of `Int(int)`, `Uint(unsigned)`, `Int64(int64_t)`, `Uint64(uint64_t)` and `Double(double)`. If `kParseNumbersAsStrings` is enabled, `Reader` will always calls `RawNumber()` instead.
124
125 `String(const char* str, SizeType length, bool copy)` is called when the `Reader` encounters a string. The first parameter is pointer to the string. The second parameter is the length of the string (excluding the null terminator). Note that RapidJSON supports null character `'\0'` inside a string. If such situation happens, `strlen(str) < length`. The last `copy` indicates whether the handler needs to make a copy of the string. For normal parsing, `copy = true`. Only when *insitu* parsing is used, `copy = false`. And beware that, the character type depends on the target encoding, which will be explained later.
126
127 When the `Reader` encounters the beginning of an object, it calls `StartObject()`. An object in JSON is a set of name-value pairs. If the object contains members it first calls `Key()` for the name of member, and then calls functions depending on the type of the value. These calls of name-value pairs repeats until calling `EndObject(SizeType memberCount)`. Note that the `memberCount` parameter is just an aid for the handler, user may not need this parameter.
128
129 Array is similar to object but simpler. At the beginning of an array, the `Reader` calls `BeginArary()`. If there is elements, it calls functions according to the types of element. Similarly, in the last call `EndArray(SizeType elementCount)`, the parameter `elementCount` is just an aid for the handler.
130
131 Every handler functions returns a `bool`. Normally it should returns `true`. If the handler encounters an error, it can return `false` to notify event publisher to stop further processing.
132
133 For example, when we parse a JSON with `Reader` and the handler detected that the JSON does not conform to the required schema, then the handler can return `false` and let the `Reader` stop further parsing. And the `Reader` will be in error state with error code `kParseErrorTermination`.
134
135 ## GenericReader {#GenericReader}
136
137 As mentioned before, `Reader` is a typedef of a template class `GenericReader`:
138
139 ~~~~~~~~~~cpp
140 namespace rapidjson {
141
142 template <typename SourceEncoding, typename TargetEncoding, typename Allocator = MemoryPoolAllocator<> >
143 class GenericReader {
144 // ...
145 };
146
147 typedef GenericReader<UTF8<>, UTF8<> > Reader;
148
149 } // namespace rapidjson
150 ~~~~~~~~~~
151
152 The `Reader` uses UTF-8 as both source and target encoding. The source encoding means the encoding in the JSON stream. The target encoding means the encoding of the `str` parameter in `String()` calls. For example, to parse a UTF-8 stream and outputs UTF-16 string events, you can define a reader by:
153
154 ~~~~~~~~~~cpp
155 GenericReader<UTF8<>, UTF16<> > reader;
156 ~~~~~~~~~~
157
158 Note that, the default character type of `UTF16` is `wchar_t`. So this `reader`needs to call `String(const wchar_t*, SizeType, bool)` of the handler.
159
160 The third template parameter `Allocator` is the allocator type for internal data structure (actually a stack).
161
162 ## Parsing {#SaxParsing}
163
164 The one and only one function of `Reader` is to parse JSON.
165
166 ~~~~~~~~~~cpp
167 template <unsigned parseFlags, typename InputStream, typename Handler>
168 bool Parse(InputStream& is, Handler& handler);
169
170 // with parseFlags = kDefaultParseFlags
171 template <typename InputStream, typename Handler>
172 bool Parse(InputStream& is, Handler& handler);
173 ~~~~~~~~~~
174
175 If an error occurs during parsing, it will return `false`. User can also calls `bool HasParseEror()`, `ParseErrorCode GetParseErrorCode()` and `size_t GetErrorOffset()` to obtain the error states. Actually `Document` uses these `Reader` functions to obtain parse errors. Please refer to [DOM](doc/dom.md) for details about parse error.
176
177 # Writer {#Writer}
178
179 `Reader` converts (parses) JSON into events. `Writer` does exactly the opposite. It converts events into JSON.
180
181 `Writer` is very easy to use. If your application only need to converts some data into JSON, it may be a good choice to use `Writer` directly, instead of building a `Document` and then stringifying it with a `Writer`.
182
183 In `simplewriter` example, we do exactly the reverse of `simplereader`.
184
185 ~~~~~~~~~~cpp
186 #include "rapidjson/writer.h"
187 #include "rapidjson/stringbuffer.h"
188 #include <iostream>
189
190 using namespace rapidjson;
191 using namespace std;
192
193 void main() {
194 StringBuffer s;
195 Writer<StringBuffer> writer(s);
196
197 writer.StartObject();
198 writer.Key("hello");
199 writer.String("world");
200 writer.Key("t");
201 writer.Bool(true);
202 writer.Key("f");
203 writer.Bool(false);
204 writer.Key("n");
205 writer.Null();
206 writer.Key("i");
207 writer.Uint(123);
208 writer.Key("pi");
209 writer.Double(3.1416);
210 writer.Key("a");
211 writer.StartArray();
212 for (unsigned i = 0; i < 4; i++)
213 writer.Uint(i);
214 writer.EndArray();
215 writer.EndObject();
216
217 cout << s.GetString() << endl;
218 }
219 ~~~~~~~~~~
220
221 ~~~~~~~~~~
222 {"hello":"world","t":true,"f":false,"n":null,"i":123,"pi":3.1416,"a":[0,1,2,3]}
223 ~~~~~~~~~~
224
225 There are two `String()` and `Key()` overloads. One is the same as defined in handler concept with 3 parameters. It can handle string with null characters. Another one is the simpler version used in the above example.
226
227 Note that, the example code does not pass any parameters in `EndArray()` and `EndObject()`. An `SizeType` can be passed but it will be simply ignored by `Writer`.
228
229 You may doubt that, why not just using `sprintf()` or `std::stringstream` to build a JSON?
230
231 There are various reasons:
232 1. `Writer` must output a well-formed JSON. If there is incorrect event sequence (e.g. `Int()` just after `StartObject()`), it generates assertion fail in debug mode.
233 2. `Writer::String()` can handle string escaping (e.g. converting code point `U+000A` to `\n`) and Unicode transcoding.
234 3. `Writer` handles number output consistently.
235 4. `Writer` implements the event handler concept. It can be used to handle events from `Reader`, `Document` or other event publisher.
236 5. `Writer` can be optimized for different platforms.
237
238 Anyway, using `Writer` API is even simpler than generating a JSON by ad hoc methods.
239
240 ## Template {#WriterTemplate}
241
242 `Writer` has a minor design difference to `Reader`. `Writer` is a template class, not a typedef. There is no `GenericWriter`. The following is the declaration.
243
244 ~~~~~~~~~~cpp
245 namespace rapidjson {
246
247 template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename Allocator = CrtAllocator<>, unsigned writeFlags = kWriteDefaultFlags>
248 class Writer {
249 public:
250 Writer(OutputStream& os, Allocator* allocator = 0, size_t levelDepth = kDefaultLevelDepth)
251 // ...
252 };
253
254 } // namespace rapidjson
255 ~~~~~~~~~~
256
257 The `OutputStream` template parameter is the type of output stream. It cannot be deduced and must be specified by user.
258
259 The `SourceEncoding` template parameter specifies the encoding to be used in `String(const Ch*, ...)`.
260
261 The `TargetEncoding` template parameter specifies the encoding in the output stream.
262
263 The `Allocator` is the type of allocator, which is used for allocating internal data structure (a stack).
264
265 The `writeFlags` are combination of the following bit-flags:
266
267 Parse flags | Meaning
268 ------------------------------|-----------------------------------
269 `kWriteNoFlags` | No flag is set.
270 `kWriteDefaultFlags` | Default write flags. It is equal to macro `RAPIDJSON_WRITE_DEFAULT_FLAGS`, which is defined as `kWriteNoFlags`.
271 `kWriteValidateEncodingFlag` | Validate encoding of JSON strings.
272 `kWriteNanAndInfFlag` | Allow writing of `Infinity`, `-Infinity` and `NaN`.
273
274 Besides, the constructor of `Writer` has a `levelDepth` parameter. This parameter affects the initial memory allocated for storing information per hierarchy level.
275
276 ## PrettyWriter {#PrettyWriter}
277
278 While the output of `Writer` is the most condensed JSON without white-spaces, suitable for network transfer or storage, it is not easily readable by human.
279
280 Therefore, RapidJSON provides a `PrettyWriter`, which adds indentation and line feeds in the output.
281
282 The usage of `PrettyWriter` is exactly the same as `Writer`, expect that `PrettyWriter` provides a `SetIndent(Ch indentChar, unsigned indentCharCount)` function. The default is 4 spaces.
283
284 ## Completeness and Reset {#CompletenessReset}
285
286 A `Writer` can only output a single JSON, which can be any JSON type at the root. Once the singular event for root (e.g. `String()`), or the last matching `EndObject()` or `EndArray()` event, is handled, the output JSON is well-formed and complete. User can detect this state by calling `Writer::IsComplete()`.
287
288 When a JSON is complete, the `Writer` cannot accept any new events. Otherwise the output will be invalid (i.e. having more than one root). To reuse the `Writer` object, user can call `Writer::Reset(OutputStream& os)` to reset all internal states of the `Writer` with a new output stream.
289
290 # Techniques {#SaxTechniques}
291
292 ## Parsing JSON to Custom Data Structure {#CustomDataStructure}
293
294 `Document`'s parsing capability is completely based on `Reader`. Actually `Document` is a handler which receives events from a reader to build a DOM during parsing.
295
296 User may uses `Reader` to build other data structures directly. This eliminates building of DOM, thus reducing memory and improving performance.
297
298 In the following `messagereader` example, `ParseMessages()` parses a JSON which should be an object with key-string pairs.
299
300 ~~~~~~~~~~cpp
301 #include "rapidjson/reader.h"
302 #include "rapidjson/error/en.h"
303 #include <iostream>
304 #include <string>
305 #include <map>
306
307 using namespace std;
308 using namespace rapidjson;
309
310 typedef map<string, string> MessageMap;
311
312 struct MessageHandler
313 : public BaseReaderHandler<UTF8<>, MessageHandler> {
314 MessageHandler() : state_(kExpectObjectStart) {
315 }
316
317 bool StartObject() {
318 switch (state_) {
319 case kExpectObjectStart:
320 state_ = kExpectNameOrObjectEnd;
321 return true;
322 default:
323 return false;
324 }
325 }
326
327 bool String(const char* str, SizeType length, bool) {
328 switch (state_) {
329 case kExpectNameOrObjectEnd:
330 name_ = string(str, length);
331 state_ = kExpectValue;
332 return true;
333 case kExpectValue:
334 messages_.insert(MessageMap::value_type(name_, string(str, length)));
335 state_ = kExpectNameOrObjectEnd;
336 return true;
337 default:
338 return false;
339 }
340 }
341
342 bool EndObject(SizeType) { return state_ == kExpectNameOrObjectEnd; }
343
344 bool Default() { return false; } // All other events are invalid.
345
346 MessageMap messages_;
347 enum State {
348 kExpectObjectStart,
349 kExpectNameOrObjectEnd,
350 kExpectValue,
351 }state_;
352 std::string name_;
353 };
354
355 void ParseMessages(const char* json, MessageMap& messages) {
356 Reader reader;
357 MessageHandler handler;
358 StringStream ss(json);
359 if (reader.Parse(ss, handler))
360 messages.swap(handler.messages_); // Only change it if success.
361 else {
362 ParseErrorCode e = reader.GetParseErrorCode();
363 size_t o = reader.GetErrorOffset();
364 cout << "Error: " << GetParseError_En(e) << endl;;
365 cout << " at offset " << o << " near '" << string(json).substr(o, 10) << "...'" << endl;
366 }
367 }
368
369 int main() {
370 MessageMap messages;
371
372 const char* json1 = "{ \"greeting\" : \"Hello!\", \"farewell\" : \"bye-bye!\" }";
373 cout << json1 << endl;
374 ParseMessages(json1, messages);
375
376 for (MessageMap::const_iterator itr = messages.begin(); itr != messages.end(); ++itr)
377 cout << itr->first << ": " << itr->second << endl;
378
379 cout << endl << "Parse a JSON with invalid schema." << endl;
380 const char* json2 = "{ \"greeting\" : \"Hello!\", \"farewell\" : \"bye-bye!\", \"foo\" : {} }";
381 cout << json2 << endl;
382 ParseMessages(json2, messages);
383
384 return 0;
385 }
386 ~~~~~~~~~~
387
388 ~~~~~~~~~~
389 { "greeting" : "Hello!", "farewell" : "bye-bye!" }
390 farewell: bye-bye!
391 greeting: Hello!
392
393 Parse a JSON with invalid schema.
394 { "greeting" : "Hello!", "farewell" : "bye-bye!", "foo" : {} }
395 Error: Terminate parsing due to Handler error.
396 at offset 59 near '} }...'
397 ~~~~~~~~~~
398
399 The first JSON (`json1`) was successfully parsed into `MessageMap`. Since `MessageMap` is a `std::map`, the printing order are sorted by the key. This order is different from the JSON's order.
400
401 In the second JSON (`json2`), `foo`'s value is an empty object. As it is an object, `MessageHandler::StartObject()` will be called. However, at that moment `state_ = kExpectValue`, so that function returns `false` and cause the parsing process be terminated. The error code is `kParseErrorTermination`.
402
403 ## Filtering of JSON {#Filtering}
404
405 As mentioned earlier, `Writer` can handle the events published by `Reader`. `condense` example simply set a `Writer` as handler of a `Reader`, so it can remove all white-spaces in JSON. `pretty` example uses the same relationship, but replacing `Writer` by `PrettyWriter`. So `pretty` can be used to reformat a JSON with indentation and line feed.
406
407 Actually, we can add intermediate layer(s) to filter the contents of JSON via these SAX-style API. For example, `capitalize` example capitalize all strings in a JSON.
408
409 ~~~~~~~~~~cpp
410 #include "rapidjson/reader.h"
411 #include "rapidjson/writer.h"
412 #include "rapidjson/filereadstream.h"
413 #include "rapidjson/filewritestream.h"
414 #include "rapidjson/error/en.h"
415 #include <vector>
416 #include <cctype>
417
418 using namespace rapidjson;
419
420 template<typename OutputHandler>
421 struct CapitalizeFilter {
422 CapitalizeFilter(OutputHandler& out) : out_(out), buffer_() {
423 }
424
425 bool Null() { return out_.Null(); }
426 bool Bool(bool b) { return out_.Bool(b); }
427 bool Int(int i) { return out_.Int(i); }
428 bool Uint(unsigned u) { return out_.Uint(u); }
429 bool Int64(int64_t i) { return out_.Int64(i); }
430 bool Uint64(uint64_t u) { return out_.Uint64(u); }
431 bool Double(double d) { return out_.Double(d); }
432 bool RawNumber(const char* str, SizeType length, bool copy) { return out_.RawNumber(str, length, copy); }
433 bool String(const char* str, SizeType length, bool) {
434 buffer_.clear();
435 for (SizeType i = 0; i < length; i++)
436 buffer_.push_back(std::toupper(str[i]));
437 return out_.String(&buffer_.front(), length, true); // true = output handler need to copy the string
438 }
439 bool StartObject() { return out_.StartObject(); }
440 bool Key(const char* str, SizeType length, bool copy) { return String(str, length, copy); }
441 bool EndObject(SizeType memberCount) { return out_.EndObject(memberCount); }
442 bool StartArray() { return out_.StartArray(); }
443 bool EndArray(SizeType elementCount) { return out_.EndArray(elementCount); }
444
445 OutputHandler& out_;
446 std::vector<char> buffer_;
447 };
448
449 int main(int, char*[]) {
450 // Prepare JSON reader and input stream.
451 Reader reader;
452 char readBuffer[65536];
453 FileReadStream is(stdin, readBuffer, sizeof(readBuffer));
454
455 // Prepare JSON writer and output stream.
456 char writeBuffer[65536];
457 FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
458 Writer<FileWriteStream> writer(os);
459
460 // JSON reader parse from the input stream and let writer generate the output.
461 CapitalizeFilter<Writer<FileWriteStream> > filter(writer);
462 if (!reader.Parse(is, filter)) {
463 fprintf(stderr, "\nError(%u): %s\n", (unsigned)reader.GetErrorOffset(), GetParseError_En(reader.GetParseErrorCode()));
464 return 1;
465 }
466
467 return 0;
468 }
469 ~~~~~~~~~~
470
471 Note that, it is incorrect to simply capitalize the JSON as a string. For example:
472 ~~~~~~~~~~
473 ["Hello\nWorld"]
474 ~~~~~~~~~~
475
476 Simply capitalizing the whole JSON would contain incorrect escape character:
477 ~~~~~~~~~~
478 ["HELLO\NWORLD"]
479 ~~~~~~~~~~
480
481 The correct result by `capitalize`:
482 ~~~~~~~~~~
483 ["HELLO\nWORLD"]
484 ~~~~~~~~~~
485
486 More complicated filters can be developed. However, since SAX-style API can only provide information about a single event at a time, user may need to book-keeping the contextual information (e.g. the path from root value, storage of other related values). Some processing may be easier to be implemented in DOM than SAX.