首页 > 解决方案 > 使用Qt将javascript转储数组解析为点列表

问题描述

我需要使用 c++ 将转储的点数组转换为 qt 中的点列表,以便进一步调试我的应用程序。我使用 chrome 将数组对象复制到一个文件中,它最终会像这样:

[
  {
    "x": 0,
    "y": 266.48351648351644
  },
  {
    "x": 2.3095238095238093,
    "y": 274.3003663003663
  },
  {
    "x": 3.3754578754578755,
    "y": 277.6758241758242
  }
]

我的策略是打开文件并找到其中包含字符 x 或 y 的行,并将每个连续的 x,y 保存在一个点对象中:

void MainWindow::on_btnOpenFile_clicked()
{

    auto path = QFileDialog::getOpenFileName(this, "Browse for a array object file...");
    QFile file(path); // works fine

    if(file.exists(path) && file.open(QIODevice::ReadOnly)) {

        QTextStream stream(&file);
        QVector<QPointF> points;
        QString currentLine;
        qreal x;
        qreal y;

        // Regex rules for x and y
        QRegExp rX(":.*,");
        rX.setMinimal(true);
        QRegExp rY(":.*");
        rY.setMinimal(true);

        while(!stream.atEnd()) {

            bool xFound = false, yFound = false;
            currentLine = stream.readLine();

            // Get X value
            if(currentLine.contains("x", Qt::CaseInsensitive)) {
                auto pos = rX.indexIn(currentLine);
                if(pos == 0) {
                    x = rX.capturedTexts()[0].toDouble();
                    xFound = true;
                }
            } else if(currentLine.contains("y", Qt::CaseInsensitive)) { // Get Y value
                auto pos = rY.indexIn(currentLine);
                if(pos == 0) {
                    y = rY.capturedTexts()[0].toDouble();
                    yFound = true;
                }
            }

            if(xFound)
            points.push_back({x,y});

        }
    }

}

我只是注意到我的方法行不通,因为我只在 while 循环的每次迭代中评估一行......而且这永远不会奏效。

其次是我的正则表达式,它甚至与[字符匹配!

有没有更聪明的方法来做这个解析?转储的文件对我来说看起来像 JSON,但可能不是?如果它与 JSON 兼容,是否有一种自动转换它的方法?

标签: c++regexqtparsing

解决方案


你正在尝试重新发明轮子。不要尝试为此使用正则表达式。将文件读入 JSON 文档。像这样的东西应该可以工作(未经测试):

    QFile file("myfile.json");
    QVector<QPointF> points;

    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
        file.close();

        QJsonArray array = doc.array();

        for (auto &&point : array)
        {
            QJsonObject p = point.toObject();
            points.push_back({p["x"], p["y"]});
        }
    }

推荐阅读