Wie man jsonlines mit boost::json parst (minimales Beispiel)
Das folgende Beispiel zeigt, wie man eine jsonlines-Datei mit boost::json parst. Da eine jsonlines-Datei nur eine Folge von Zeilen ist, jede mit einem JSON-Objekt, können wir die Funktion boost::json::parse verwenden, um jede Zeile ohne besondere Aktionen zu parsen.
Dieser Code kann eine 4,5 GB jsonlines-Datei mit 4442720 Zeilen in 42 Sekunden auf meinem i7-6700-Desktop parsen (die Ausgabe wurde für diesen Benchmark deaktiviert).
#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 object
std::cout << "Processing JSON object: " << boost::json::serialize(obj) << 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;
}Kompilieren Sie so:
g++ -std=c++17 -march=native -O3 -o jsonlines_parser jsonlines_parser.cpp -lboost_json-march=native und -O3 sind optional, aber sie können den Parsing-Prozess beschleunigen. Beachten Sie, dass -march=native das Binary nicht portabel macht, da es kompiliert wurde, um auf Prozessoren mit der gleichen Architektur wie dem, auf dem Sie kompilieren, zu laufen. Siehe die -march-Dokumentation für weitere Informationen.