Repository navigation
Expand file tree
/
Copy path08_streaming.cpp
More file actions
69 lines (61 loc) · 2.34 KB
/
Copy path08_streaming.cpp
File metadata and controls
69 lines (61 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//
// Copyright 2025 ByteDance Ltd. and/or its affiliates. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License").
//
//===----------------------------------------------------------------------===//
// 08 — Process a JSON stream without building an in-memory document.
// Referenced by docs/11-streaming.md.
//
#include "pjson.h"
#include "pjson_parser.h"
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <sstream>
using namespace ByteDance;
// SAX handler that summarizes every JSON number encountered anywhere in the
// stream. Unoverridden callbacks accept and ignore non-numeric events.
struct NumberSummary : pJsonParser::SaxHandler {
size_t count = 0;
double total = 0.0;
// Count an integer event and continue parsing.
bool onInt(int64_t value) override {
++count;
total += static_cast<double>(value);
return true;
}
// Count a floating-point event and continue parsing.
bool onDouble(double value) override {
++count;
total += value;
return true;
}
};
// Streams an input through the SAX summary, then streams a small DOM report to
// standard output without constructing either whole-document output string.
int main() {
// --- Incremental input -------------------------------------------------
std::istringstream input(R"({"readings":[10,12.5,8,9.5]})");
NumberSummary summary;
pJsonParser::Error error;
if (!pJsonParser().parseSaxStream(input, summary, error)) {
std::cerr << error.line << ':' << error.column << ": " << error.message << '\n';
return 1;
}
std::cout << "numbers: " << summary.count << "\nsum: " << summary.total << '\n';
// --- Streaming output -------------------------------------------------
// write(out, options) serializes an existing DOM without first building a
// complete output string. Check the stream after the void-returning call.
pjson report;
report["numbers"] = static_cast<int64_t>(summary.count);
report["sum"] = summary.total;
pjson::SerializeOptions options = pjson::SerializeOptions::prettyPrinted();
options.indentWidth = 2;
options.escapeNonAscii = true;
options.maxOutputBytes = size_t(64) * 1024 * 1024;
report.write(std::cout, options);
std::cout << '\n';
if (!std::cout)
return 1;
return 0;
}