sax.md 20.8 KB
Newer Older
miloyip's avatar
miloyip committed
1
# SAX
Milo Yip's avatar
Milo Yip committed
2

Milo Yip's avatar
Milo Yip committed
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.
Milo Yip's avatar
Milo Yip committed
4

Milo Yip's avatar
Milo Yip committed
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.
Milo Yip's avatar
Milo Yip committed
6

Milo Yip's avatar
Milo Yip committed
7
[TOC]
Milo Yip's avatar
Milo Yip committed
8

Milo Yip's avatar
Milo Yip committed
9 10
# Reader {#Reader}

StilesCrisis's avatar
StilesCrisis committed
11
`Reader` parses a JSON from a stream. While it reads characters from the stream, it analyzes the characters according to the syntax of JSON, and publishes events to a handler.
Milo Yip's avatar
Milo Yip committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

For example, here is a JSON.

~~~~~~~~~~js
{
    "hello": "world",
    "t": true ,
    "f": false,
    "n": null,
    "i": 123,
    "pi": 3.1416,
    "a": [1, 2, 3, 4]
}
~~~~~~~~~~

StilesCrisis's avatar
StilesCrisis committed
27
When a `Reader` parses this JSON, it publishes the following events to the handler sequentially:
Milo Yip's avatar
Milo Yip committed
28 29

~~~~~~~~~~
30 31
StartObject()
Key("hello", 5, true)
Milo Yip's avatar
Milo Yip committed
32
String("world", 5, true)
33
Key("t", 1, true)
Milo Yip's avatar
Milo Yip committed
34
Bool(true)
35
Key("f", 1, true)
Milo Yip's avatar
Milo Yip committed
36
Bool(false)
37
Key("n", 1, true)
Milo Yip's avatar
Milo Yip committed
38
Null()
39
Key("i")
Milo Yip's avatar
Milo Yip committed
40
UInt(123)
41
Key("pi")
Milo Yip's avatar
Milo Yip committed
42
Double(3.1416)
43 44
Key("a")
StartArray()
Milo Yip's avatar
Milo Yip committed
45 46 47 48 49 50 51 52
Uint(1)
Uint(2)
Uint(3)
Uint(4)
EndArray(4)
EndObject(7)
~~~~~~~~~~

StilesCrisis's avatar
StilesCrisis committed
53
These events can be easily matched with the JSON, but some event parameters need further explanation. Let's see the `simplereader` example which produces exactly the same output as above:
Milo Yip's avatar
Milo Yip committed
54 55 56 57 58 59 60 61

~~~~~~~~~~cpp
#include "rapidjson/reader.h"
#include <iostream>

using namespace rapidjson;
using namespace std;

62
struct MyHandler : public BaseReaderHandler<UTF8<>, MyHandler> {
Milo Yip's avatar
Milo Yip committed
63 64 65 66 67 68 69 70 71 72 73 74
    bool Null() { cout << "Null()" << endl; return true; }
    bool Bool(bool b) { cout << "Bool(" << boolalpha << b << ")" << endl; return true; }
    bool Int(int i) { cout << "Int(" << i << ")" << endl; return true; }
    bool Uint(unsigned u) { cout << "Uint(" << u << ")" << endl; return true; }
    bool Int64(int64_t i) { cout << "Int64(" << i << ")" << endl; return true; }
    bool Uint64(uint64_t u) { cout << "Uint64(" << u << ")" << endl; return true; }
    bool Double(double d) { cout << "Double(" << d << ")" << endl; return true; }
    bool String(const char* str, SizeType length, bool copy) { 
        cout << "String(" << str << ", " << length << ", " << boolalpha << copy << ")" << endl;
        return true;
    }
    bool StartObject() { cout << "StartObject()" << endl; return true; }
75 76 77 78
    bool Key(const char* str, SizeType length, bool copy) { 
        cout << "Key(" << str << ", " << length << ", " << boolalpha << copy << ")" << endl;
        return true;
    }
Milo Yip's avatar
Milo Yip committed
79 80 81
    bool EndObject(SizeType memberCount) { cout << "EndObject(" << memberCount << ")" << endl; return true; }
    bool StartArray() { cout << "StartArray()" << endl; return true; }
    bool EndArray(SizeType elementCount) { cout << "EndArray(" << elementCount << ")" << endl; return true; }
Milo Yip's avatar
Milo Yip committed
82 83 84
};

void main() {
Milo Yip's avatar
Milo Yip committed
85
    const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } ";
Milo Yip's avatar
Milo Yip committed
86 87

    MyHandler handler;
Milo Yip's avatar
Milo Yip committed
88
    Reader reader;
Milo Yip's avatar
Milo Yip committed
89 90 91 92 93
    StringStream ss(json);
    reader.Parse(ss, handler);
}
~~~~~~~~~~

StilesCrisis's avatar
StilesCrisis committed
94
Note that RapidJSON uses templates to statically bind the `Reader` type and the handler type, instead of using classes with virtual functions. This paradigm can improve performance by inlining functions.
Milo Yip's avatar
Milo Yip committed
95 96 97

## Handler {#Handler}

StilesCrisis's avatar
StilesCrisis committed
98
As shown in the previous example, the user needs to implement a handler which consumes the events (via function calls) from the `Reader`. The handler must contain the following member functions.
Milo Yip's avatar
Milo Yip committed
99 100

~~~~~~~~~~cpp
101
class Handler {
Milo Yip's avatar
Milo Yip committed
102 103 104 105 106 107 108
    bool Null();
    bool Bool(bool b);
    bool Int(int i);
    bool Uint(unsigned i);
    bool Int64(int64_t i);
    bool Uint64(uint64_t i);
    bool Double(double d);
109
    bool RawNumber(const Ch* str, SizeType length, bool copy);
Milo Yip's avatar
Milo Yip committed
110 111
    bool String(const Ch* str, SizeType length, bool copy);
    bool StartObject();
112
    bool Key(const Ch* str, SizeType length, bool copy);
Milo Yip's avatar
Milo Yip committed
113 114 115
    bool EndObject(SizeType memberCount);
    bool StartArray();
    bool EndArray(SizeType elementCount);
Milo Yip's avatar
Milo Yip committed
116 117 118 119 120 121 122
};
~~~~~~~~~~

`Null()` is called when the `Reader` encounters a JSON null value.

`Bool(bool)` is called when the `Reader` encounters a JSON true or false value.

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.
Milo Yip's avatar
Milo Yip committed
124

StilesCrisis's avatar
StilesCrisis committed
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 be aware that the character type depends on the target encoding, which will be explained later.
Milo Yip's avatar
Milo Yip committed
126

StilesCrisis's avatar
StilesCrisis committed
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 repeat until calling `EndObject(SizeType memberCount)`. Note that the `memberCount` parameter is just an aid for the handler; users who do not need this parameter may ignore it.
Milo Yip's avatar
Milo Yip committed
128

StilesCrisis's avatar
StilesCrisis committed
129
Arrays are similar to objects, 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.
Milo Yip's avatar
Milo Yip committed
130

StilesCrisis's avatar
StilesCrisis committed
131
Every handler function returns a `bool`. Normally it should return `true`. If the handler encounters an error, it can return `false` to notify the event publisher to stop further processing.
Milo Yip's avatar
Milo Yip committed
132

StilesCrisis's avatar
StilesCrisis committed
133
For example, when we parse a JSON with `Reader` and the handler detects that the JSON does not conform to the required schema, the handler can return `false` and let the `Reader` stop further parsing. This will place the `Reader` in an error state, with error code `kParseErrorTermination`.
Milo Yip's avatar
Milo Yip committed
134

Milo Yip's avatar
Milo Yip committed
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
## GenericReader {#GenericReader}

As mentioned before, `Reader` is a typedef of a template class `GenericReader`:

~~~~~~~~~~cpp
namespace rapidjson {

template <typename SourceEncoding, typename TargetEncoding, typename Allocator = MemoryPoolAllocator<> >
class GenericReader {
    // ...
};

typedef GenericReader<UTF8<>, UTF8<> > Reader;

} // namespace rapidjson
~~~~~~~~~~

StilesCrisis's avatar
StilesCrisis committed
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 output UTF-16 string events, you can define a reader by:
Milo Yip's avatar
Milo Yip committed
153 154 155 156 157

~~~~~~~~~~cpp
GenericReader<UTF8<>, UTF16<> > reader;
~~~~~~~~~~

StilesCrisis's avatar
StilesCrisis committed
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.
Milo Yip's avatar
Milo Yip committed
159 160 161

The third template parameter `Allocator` is the allocator type for internal data structure (actually a stack).

Milo Yip's avatar
Milo Yip committed
162
## Parsing {#SaxParsing}
Milo Yip's avatar
Milo Yip committed
163

StilesCrisis's avatar
StilesCrisis committed
164
The main function of `Reader` is used to parse JSON. 
Milo Yip's avatar
Milo Yip committed
165 166 167 168 169 170 171 172 173 174

~~~~~~~~~~cpp
template <unsigned parseFlags, typename InputStream, typename Handler>
bool Parse(InputStream& is, Handler& handler);

// with parseFlags = kDefaultParseFlags
template <typename InputStream, typename Handler>
bool Parse(InputStream& is, Handler& handler);
~~~~~~~~~~

StilesCrisis's avatar
StilesCrisis committed
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
If an error occurs during parsing, it will return `false`. User can also call `bool HasParseError()`, `ParseErrorCode GetParseErrorCode()` and `size_t GetErrorOffset()` to obtain the error states. In fact, `Document` uses these `Reader` functions to obtain parse errors. Please refer to [DOM](doc/dom.md) for details about parse errors.

## Token-by-Token Parsing {#TokenByTokenParsing}

Some users may wish to parse a JSON input stream a single token at a time, instead of immediately parsing an entire document without stopping. To parse JSON this way, instead of calling `Parse`, you can use the `IterativeParse` set of functions:

~~~~~~~~~~cpp
    void IterativeParseInit();
	
    template <unsigned parseFlags, typename InputStream, typename Handler>
    bool IterativeParseNext(InputStream& is, Handler& handler);

    bool IterativeParseComplete();
~~~~~~~~~~

Here is an example of iteratively parsing JSON, token by token:

~~~~~~~~~~cpp
    reader.IterativeParseInit();
    while (!reader.IterativeParseComplete()) {
StilesCrisis's avatar
StilesCrisis committed
195
        reader.IterativeParseNext<kParseDefaultFlags>(is, handler);
StilesCrisis's avatar
StilesCrisis committed
196 197 198
		// Your handler has been called once.
    }
~~~~~~~~~~
Milo Yip's avatar
Milo Yip committed
199 200 201

# Writer {#Writer}

202 203
`Reader` converts (parses) JSON into events. `Writer` does exactly the opposite. It converts events into JSON. 

204
`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`.
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220

In `simplewriter` example, we do exactly the reverse of `simplereader`.

~~~~~~~~~~cpp
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>

using namespace rapidjson;
using namespace std;

void main() {
    StringBuffer s;
    Writer<StringBuffer> writer(s);
    
    writer.StartObject();
221
    writer.Key("hello");
222
    writer.String("world");
223
    writer.Key("t");
224
    writer.Bool(true);
225
    writer.Key("f");
226
    writer.Bool(false);
227
    writer.Key("n");
228
    writer.Null();
229
    writer.Key("i");
230
    writer.Uint(123);
231
    writer.Key("pi");
232
    writer.Double(3.1416);
233
    writer.Key("a");
234 235 236 237 238 239 240 241 242 243 244 245 246 247
    writer.StartArray();
    for (unsigned i = 0; i < 4; i++)
        writer.Uint(i);
    writer.EndArray();
    writer.EndObject();

    cout << s.GetString() << endl;
}
~~~~~~~~~~

~~~~~~~~~~
{"hello":"world","t":true,"f":false,"n":null,"i":123,"pi":3.1416,"a":[0,1,2,3]}
~~~~~~~~~~

248
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.
249 250 251

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`.

252
You may doubt that, why not just using `sprintf()` or `std::stringstream` to build a JSON?
253 254 255 256

There are various reasons:
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.
2. `Writer::String()` can handle string escaping (e.g. converting code point `U+000A` to `\n`) and Unicode transcoding.
257
3. `Writer` handles number output consistently.
258 259
4. `Writer` implements the event handler concept. It can be used to handle events from `Reader`, `Document` or other event publisher.
5. `Writer` can be optimized for different platforms.
260 261 262 263 264 265 266 267 268 269

Anyway, using `Writer` API is even simpler than generating a JSON by ad hoc methods.

## Template {#WriterTemplate}

`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.

~~~~~~~~~~cpp
namespace rapidjson {

Milo Yip's avatar
Milo Yip committed
270
template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename Allocator = CrtAllocator<>, unsigned writeFlags = kWriteDefaultFlags>
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
class Writer {
public:
    Writer(OutputStream& os, Allocator* allocator = 0, size_t levelDepth = kDefaultLevelDepth)
// ...
};

} // namespace rapidjson
~~~~~~~~~~

The `OutputStream` template parameter is the type of output stream. It cannot be deduced and must be specified by user.

The `SourceEncoding` template parameter specifies the encoding to be used in `String(const Ch*, ...)`.

The `TargetEncoding` template parameter specifies the encoding in the output stream.

Milo Yip's avatar
Milo Yip committed
286 287 288 289 290 291 292 293 294 295
The `Allocator` is the type of allocator, which is used for allocating internal data structure (a stack).

The `writeFlags` are combination of the following bit-flags:

Parse flags                   | Meaning
------------------------------|-----------------------------------
`kWriteNoFlags`               | No flag is set.
`kWriteDefaultFlags`          | Default write flags. It is equal to macro `RAPIDJSON_WRITE_DEFAULT_FLAGS`, which is defined as `kWriteNoFlags`.
`kWriteValidateEncodingFlag`  | Validate encoding of JSON strings.
`kWriteNanAndInfFlag`         | Allow writing of `Infinity`, `-Infinity` and `NaN`.
296 297 298

Besides, the constructor of `Writer` has a `levelDepth` parameter. This parameter affects the initial memory allocated for storing information per hierarchy level.

Milo Yip's avatar
Milo Yip committed
299 300
## PrettyWriter {#PrettyWriter}

301 302 303 304 305 306
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.

Therefore, RapidJSON provides a `PrettyWriter`, which adds indentation and line feeds in the output.

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.

307 308
## Completeness and Reset {#CompletenessReset}

309
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()`.
310 311 312

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.

Milo Yip's avatar
Milo Yip committed
313
# Techniques {#SaxTechniques}
Milo Yip's avatar
Milo Yip committed
314 315 316 317 318 319 320

## Parsing JSON to Custom Data Structure {#CustomDataStructure}

`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.

User may uses `Reader` to build other data structures directly. This eliminates building of DOM, thus reducing memory and improving performance.

321 322
In the following `messagereader` example, `ParseMessages()` parses a JSON which should be an object with key-string pairs.

Milo Yip's avatar
Milo Yip committed
323
~~~~~~~~~~cpp
324 325 326 327 328 329
#include "rapidjson/reader.h"
#include "rapidjson/error/en.h"
#include <iostream>
#include <string>
#include <map>

Milo Yip's avatar
Milo Yip committed
330 331 332 333 334
using namespace std;
using namespace rapidjson;

typedef map<string, string> MessageMap;

335 336
struct MessageHandler
    : public BaseReaderHandler<UTF8<>, MessageHandler> {
337
    MessageHandler() : state_(kExpectObjectStart) {
Milo Yip's avatar
Milo Yip committed
338 339 340
    }

    bool StartObject() {
341 342 343 344 345
        switch (state_) {
        case kExpectObjectStart:
            state_ = kExpectNameOrObjectEnd;
            return true;
        default:
Milo Yip's avatar
Milo Yip committed
346
            return false;
347
        }
Milo Yip's avatar
Milo Yip committed
348 349
    }

350 351 352
    bool String(const char* str, SizeType length, bool) {
        switch (state_) {
        case kExpectNameOrObjectEnd:
Milo Yip's avatar
Milo Yip committed
353
            name_ = string(str, length);
354
            state_ = kExpectValue;
Milo Yip's avatar
Milo Yip committed
355
            return true;
356
        case kExpectValue:
Milo Yip's avatar
Milo Yip committed
357
            messages_.insert(MessageMap::value_type(name_, string(str, length)));
358
            state_ = kExpectNameOrObjectEnd;
Milo Yip's avatar
Milo Yip committed
359
            return true;
360
        default:
Milo Yip's avatar
Milo Yip committed
361
            return false;
362
        }
Milo Yip's avatar
Milo Yip committed
363 364
    }

365 366 367
    bool EndObject(SizeType) { return state_ == kExpectNameOrObjectEnd; }

    bool Default() { return false; } // All other events are invalid.
Milo Yip's avatar
Milo Yip committed
368 369 370 371

    MessageMap messages_;
    enum State {
        kExpectObjectStart,
372
        kExpectNameOrObjectEnd,
Milo Yip's avatar
Milo Yip committed
373
        kExpectValue,
374
    }state_;
Milo Yip's avatar
Milo Yip committed
375 376 377 378 379 380 381 382
    std::string name_;
};

void ParseMessages(const char* json, MessageMap& messages) {
    Reader reader;
    MessageHandler handler;
    StringStream ss(json);
    if (reader.Parse(ss, handler))
383 384 385 386 387 388 389
        messages.swap(handler.messages_);   // Only change it if success.
    else {
        ParseErrorCode e = reader.GetParseErrorCode();
        size_t o = reader.GetErrorOffset();
        cout << "Error: " << GetParseError_En(e) << endl;;
        cout << " at offset " << o << " near '" << string(json).substr(o, 10) << "...'" << endl;
    }
Milo Yip's avatar
Milo Yip committed
390 391
}

392
int main() {
Milo Yip's avatar
Milo Yip committed
393
    MessageMap messages;
394 395 396 397 398 399 400 401 402 403 404 405 406 407

    const char* json1 = "{ \"greeting\" : \"Hello!\", \"farewell\" : \"bye-bye!\" }";
    cout << json1 << endl;
    ParseMessages(json1, messages);

    for (MessageMap::const_iterator itr = messages.begin(); itr != messages.end(); ++itr)
        cout << itr->first << ": " << itr->second << endl;

    cout << endl << "Parse a JSON with invalid schema." << endl;
    const char* json2 = "{ \"greeting\" : \"Hello!\", \"farewell\" : \"bye-bye!\", \"foo\" : {} }";
    cout << json2 << endl;
    ParseMessages(json2, messages);

    return 0;
Milo Yip's avatar
Milo Yip committed
408 409 410 411
}
~~~~~~~~~~

~~~~~~~~~~
412 413 414 415 416 417 418 419 420 421
{ "greeting" : "Hello!", "farewell" : "bye-bye!" }
farewell: bye-bye!
greeting: Hello!

Parse a JSON with invalid schema.
{ "greeting" : "Hello!", "farewell" : "bye-bye!", "foo" : {} }
Error: Terminate parsing due to Handler error.
 at offset 59 near '} }...'
~~~~~~~~~~

422
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.
423 424

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`.
Milo Yip's avatar
Milo Yip committed
425 426

## Filtering of JSON {#Filtering}
Milo Yip's avatar
Milo Yip committed
427

428 429 430 431 432
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.

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.

~~~~~~~~~~cpp
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
#include "rapidjson/reader.h"
#include "rapidjson/writer.h"
#include "rapidjson/filereadstream.h"
#include "rapidjson/filewritestream.h"
#include "rapidjson/error/en.h"
#include <vector>
#include <cctype>

using namespace rapidjson;

template<typename OutputHandler>
struct CapitalizeFilter {
    CapitalizeFilter(OutputHandler& out) : out_(out), buffer_() {
    }

    bool Null() { return out_.Null(); }
    bool Bool(bool b) { return out_.Bool(b); }
    bool Int(int i) { return out_.Int(i); }
    bool Uint(unsigned u) { return out_.Uint(u); }
    bool Int64(int64_t i) { return out_.Int64(i); }
    bool Uint64(uint64_t u) { return out_.Uint64(u); }
    bool Double(double d) { return out_.Double(d); }
455
    bool RawNumber(const char* str, SizeType length, bool copy) { return out_.RawNumber(str, length, copy); }
456 457 458 459 460 461 462
    bool String(const char* str, SizeType length, bool) { 
        buffer_.clear();
        for (SizeType i = 0; i < length; i++)
            buffer_.push_back(std::toupper(str[i]));
        return out_.String(&buffer_.front(), length, true); // true = output handler need to copy the string
    }
    bool StartObject() { return out_.StartObject(); }
463
    bool Key(const char* str, SizeType length, bool copy) { return String(str, length, copy); }
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
    bool EndObject(SizeType memberCount) { return out_.EndObject(memberCount); }
    bool StartArray() { return out_.StartArray(); }
    bool EndArray(SizeType elementCount) { return out_.EndArray(elementCount); }

    OutputHandler& out_;
    std::vector<char> buffer_;
};

int main(int, char*[]) {
    // Prepare JSON reader and input stream.
    Reader reader;
    char readBuffer[65536];
    FileReadStream is(stdin, readBuffer, sizeof(readBuffer));

    // Prepare JSON writer and output stream.
    char writeBuffer[65536];
    FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
    Writer<FileWriteStream> writer(os);

    // JSON reader parse from the input stream and let writer generate the output.
    CapitalizeFilter<Writer<FileWriteStream> > filter(writer);
    if (!reader.Parse(is, filter)) {
        fprintf(stderr, "\nError(%u): %s\n", (unsigned)reader.GetErrorOffset(), GetParseError_En(reader.GetParseErrorCode()));
        return 1;
    }

    return 0;
}
~~~~~~~~~~

Note that, it is incorrect to simply capitalize the JSON as a string. For example:
495 496
~~~~~~~~~~
["Hello\nWorld"]
497 498 499
~~~~~~~~~~

Simply capitalizing the whole JSON would contain incorrect escape character:
500 501
~~~~~~~~~~
["HELLO\NWORLD"]
502 503 504
~~~~~~~~~~

The correct result by `capitalize`:
505 506
~~~~~~~~~~
["HELLO\nWORLD"]
507 508
~~~~~~~~~~

509
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.