1 // JSON condenser example
2
3 // This example parses JSON from stdin with validation,
4 // and re-output the JSON content to stdout with all string capitalized, and without whitespace.
5
6 #include "rapidjson/reader.h"
7 #include "rapidjson/writer.h"
8 #include "rapidjson/filereadstream.h"
9 #include "rapidjson/filewritestream.h"
10 #include "rapidjson/error/en.h"
11 #include <vector>
12 #include <cctype>
13
14 using namespace rapidjson;
15
16 template<typename OutputHandler>
17 struct CapitalizeFilter {
CapitalizeFilterCapitalizeFilter18 CapitalizeFilter(OutputHandler& out) : out_(out), buffer_() {}
19
NullCapitalizeFilter20 bool Null() { return out_.Null(); }
BoolCapitalizeFilter21 bool Bool(bool b) { return out_.Bool(b); }
IntCapitalizeFilter22 bool Int(int i) { return out_.Int(i); }
UintCapitalizeFilter23 bool Uint(unsigned u) { return out_.Uint(u); }
Int64CapitalizeFilter24 bool Int64(int64_t i) { return out_.Int64(i); }
Uint64CapitalizeFilter25 bool Uint64(uint64_t u) { return out_.Uint64(u); }
DoubleCapitalizeFilter26 bool Double(double d) { return out_.Double(d); }
StringCapitalizeFilter27 bool String(const char* str, SizeType length, bool) {
28 buffer_.clear();
29 for (SizeType i = 0; i < length; i++)
30 buffer_.push_back(std::toupper(str[i]));
31 return out_.String(&buffer_.front(), length, true); // true = output handler need to copy the string
32 }
StartObjectCapitalizeFilter33 bool StartObject() { return out_.StartObject(); }
KeyCapitalizeFilter34 bool Key(const char* str, SizeType length, bool copy) { return String(str, length, copy); }
EndObjectCapitalizeFilter35 bool EndObject(SizeType memberCount) { return out_.EndObject(memberCount); }
StartArrayCapitalizeFilter36 bool StartArray() { return out_.StartArray(); }
EndArrayCapitalizeFilter37 bool EndArray(SizeType elementCount) { return out_.EndArray(elementCount); }
38
39 OutputHandler& out_;
40 std::vector<char> buffer_;
41
42 private:
43 CapitalizeFilter(const CapitalizeFilter&);
44 CapitalizeFilter& operator=(const CapitalizeFilter&);
45 };
46
main(int,char * [])47 int main(int, char*[]) {
48 // Prepare JSON reader and input stream.
49 Reader reader;
50 char readBuffer[65536];
51 FileReadStream is(stdin, readBuffer, sizeof(readBuffer));
52
53 // Prepare JSON writer and output stream.
54 char writeBuffer[65536];
55 FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
56 Writer<FileWriteStream> writer(os);
57
58 // JSON reader parse from the input stream and let writer generate the output.
59 CapitalizeFilter<Writer<FileWriteStream> > filter(writer);
60 if (!reader.Parse(is, filter)) {
61 fprintf(stderr, "\nError(%u): %s\n", (unsigned)reader.GetErrorOffset(), GetParseError_En(reader.GetParseErrorCode()));
62 return 1;
63 }
64
65 return 0;
66 }
67