Fast & simple JSONLines processor in C++ using boost::json
This example will parse a jsonlines
file (a file with one JSON object per line) and print the name
field of each object.
This code has not specifically been optimized for performance but rather as a trade-off between performance and readability. It should be fast enough for most use cases.
#include <iostream>
#include <fstream>
#include <string>
#include <boost/json.hpp>
class JSONLineProcessor {
public:
JSONLineProcessor(const std::string& filename) : file(filename) {
if (!file.is_open()) {
throw std::runtime_error("Error: Could not open file.");
}
}
void process_lines() {
std::string line;
while (std::getline(file, line)) {
process_line(line);
}
}
private:
std::ifstream file;
void process_line(const std::string& line) {
try {
// Parse the JSON line
boost::json::value json_value = boost::json::parse(line);
// Check if it's a JSON object
if (json_value.is_object()) {
process_json(json_value.as_object());
} else {
std::cerr << "Error: Parsed value is not a JSON object." << std::endl;
}
} catch (const boost::json::system_error& e) {
// Handle parsing errors
std::cerr << "Error parsing JSON line: " << e.what() << std::endl;
}
}
void process_json(const boost::json::object& obj) {
// For the sake of example, just print the json["timestamp"] value
auto _timestamp = obj.at("timestamp");
if (_timestamp.is_double()) {
double timestamp = obj.at("timestamp").as_double();
std::cout << obj.at("timestamp").as_double() << std::endl;
}
}
};
int main(int argc, char** argv) {
if(argc <= 1) {
std::cerr << "Usage: " << argv[0] << std::endl;
return 1;
}
try {
JSONLineProcessor processor(argv[1]);
processor.process_lines();
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
How to compile
g++ -O3 -std=c++17 -lboost_json -o jsonlines_processor jsonlines_processor.cpp
Performance
Compiling with
g++ -march=native -O2 -std=gnu++17 -lboost_json -o jsonlines_processor jsonlines_processor.cpp
and running with
time ./jsonlines_processor filename.jsonlines > /dev/null
on a 4.5GB jsonlines file with 4442720
(4.4M) lines takes 36.4
seconds (best of 3 runs), yielding a throughput of 123.6
MB/s and 122k
JSON lines per second on my Intel(R) Core(TM) i7-6700 CPU @ 3.40GHz
.
This program does not utilize multi-threading