我正在尝试使用simdjson库:https://github.com/simdjson/simdjson#documentation

但是,我需要解析的json来自websocket连接,并不总是包含相同的键。因此,有时尝试通过键从已解析的json对象中提取值会引发异常:

terminate called after throwing an instance of 'simdjson::simdjson_error'
  what():  The JSON field referenced does not exist in this object.
Aborted (core dumped)

下面的示例代码试图使异常处理起作用:
#include <iostream>
#include <string>
#include <chrono>

#include "simdjson.h"

using namespace std;
using namespace simdjson;

int main() {

    auto cars_json = R"( [
  { "make": "Toyota", "model": "Camry",  "year": 2018, "tire_pressure": [ 40.1, 39.9, 37.7, 40.4 ] },
  { "make": "Kia",    "model": "Soul",   "year": 2012, "tire_pressure": [ 30.1, 31.0, 28.6, 28.7 ] },
  { "make": "Toyota", "model": "Tercel", "year": 1999, "tire_pressure": [ 29.8, 30.0, 30.2, 30.5 ] }
] )"_padded;

    simdjson::error_code error_c;

    dom::parser  parser;
    dom::object  doc;
    dom::element elem;

    const char* value;

    doc = parser.parse(cars_json);

    try
    {
        doc["clOrdID"].get<const char*>().tie(value, error_c);
    }
    catch (simdjson_error e)
    {
        cout << 1 << endl;
    }

    return 0;
}

我在这里阅读了有关库错误处理的文档:
https://github.com/simdjson/simdjson/blob/master/doc/basics.md#error-handling

但是,使用try-catch块和上面的文档中描述的错误处理方法仍然会导致程序退出。我是C++编程的新手,因此也使用该语言处理异常-关于如何从该库中捕获任何异常的任何指导将不胜感激!

最佳答案

首先,您应该将parser.parse(cars_json);移到try / catch块中,以捕获解析器异常

try {
    doc = parser.parse(cars_json);
} catch (simdjson::simdjson_error e) {
    cout << e.what() << endl;
}
那么您可能会意识到parser不会返回simdjson::dom::object,而是返回simdjson::dom::array
这是转换为const char*的更新示例
const char* value;

try {
    auto root = parser.parse(cars_json);
    cout << "root: " << root.type() << endl;

    auto car = root.at(0);
    if(car["make"].is_string()){
        cout << "first car: " << car["make"] << endl;
    }

    //check non-existing element
    if(car["foo"].is_string()){
        // exception won't be thrown
    }

    std::string_view sv = root.at(1)["model"];
    cout << "string view: " << sv << endl;
    //conversion to const char*
    value = std::string(sv).c_str();
    cout << "const char: " << value << endl;


} catch (const simdjson::simdjson_error &e) {
    cout << e.what() << endl;
}
输出应为:
root: array
first car: "Toyota"
string view: Soul
const char: Soul

10-01 08:18