使用 QT 逐行读取 JSON

read JSON line by line with QT

本文关键字:JSON 读取 逐行 QT 使用      更新时间:2023-10-16

我有一个这样的JSON:

{
"09:32 24.09.2018": "456",
"09:56 24.09.2018": "854",
"09:57 24.09.2018": "854",
"09:59 24.09.2018": "853",
"10:00 24.09.2018": "369",
"10:01 24.09.2018": "369"
}

如何在 QT5 中逐行阅读此内容。我想把它写成QTableWidget,在第一行/第一列有"09:32 24.09.2018",在第一行/第二列有"456",在第一行/第二列有"09:56 24.09.2018"第二行/第一列等等。

我当前的加载工作方式如下:

QJsonDocument getFile = loadJson("test");
QJsonObject obj = getFile.object();

跟:

QJsonDocument MainWindow::loadJson(QString fileName) {
QFile jsonFile(fileName);
jsonFile.open(QFile::ReadOnly);
return QJsonDocument().fromJson(jsonFile.readAll());
}

谢谢。

你可以遍历QJsonObject来横向它:

QString val;
QFile file;
//set the file name
file.setFileName("foo.json");
//open the file name
file.open(QIODevice::ReadOnly | QIODevice::Text);
//read the file name
val = file.readAll();
//close the file name
file.close();
//string to json doc
QJsonDocument doc = QJsonDocument::fromJson(val.toUtf8());
//json doc to json object
QJsonObject object = doc.object();
//json object can be iterated
for (auto it = object.begin(), end=object.end(); it != end; ++it)
{
qDebug() << "Key: " << it.key() << "Val: " << it.value();
}