Qt读写JSON文件

将QProcess的执行输出写入JSON文件

要将 QProcess 执行输出写入 JSON 文件,首先需要捕获 QProcess 的标准输出,然后将该输出处理为 JSON 格式并保存到文件中。在 Qt 中,您可以使用 QJsonDocument 来处理 JSON 数据,并将其写入文件。

示例代码:将 QProcess 执行输出写入 JSON 文件

假设 Dependencies.exe 输出的是 JSON 格式的数据,下面的代码展示了如何执行该程序,获取输出,并将其保存为 JSON 文件。

cpp 复制代码
#include <QCoreApplication>
#include <QProcess>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>

class WorkerThread : public QThread
{
    Q_OBJECT

protected:
    void run() override {
        // 创建 QProcess 实例
        QProcess process;

        // 设置要执行的程序和参数
        QString program = "Dependencies.exe";  // 可执行程序的文件名
        QStringList arguments;
        arguments << "-json"  // 参数 -json
                  << "-depth" << "1"  // 参数 -depth 1
                  << "-chain"  // 参数 -chain
                  << "D:/syncservice_digital/build/bin/Release/src/bin/device/fs3scan.2.0.0.dll";  // DLL 路径

        // 设置工作目录
        process.setWorkingDirectory("D:/syncservice_digital/build/bin/Release/src/bin/device");

        // 启动程序
        process.start(program, arguments);

        // 检查程序是否启动成功
        if (!process.waitForStarted()) {
            qDebug() << "Failed to start the process";
            return;
        }

        // 等待程序执行完成
        if (!process.waitForFinished()) {
            qDebug() << "Process failed to finish";
            return;
        }

        // 获取标准输出(假设输出是 JSON 格式)
        QString output = process.readAllStandardOutput();

        // 打印输出,调试用
        qDebug() << "Process output:" << output;

        // 解析 JSON 数据
        QJsonDocument jsonDoc = QJsonDocument::fromJson(output.toUtf8());

        // 检查 JSON 是否有效
        if (jsonDoc.isNull()) {
            qDebug() << "Invalid JSON data";
            return;
        }

        // 将 JSON 数据保存到文件
        QFile file("output.json");
        if (file.open(QIODevice::WriteOnly)) {
            file.write(jsonDoc.toJson(QJsonDocument::Indented));  // 保存为格式化的 JSON
            file.close();
            qDebug() << "JSON output written to output.json";
        } else {
            qDebug() << "Failed to open file for writing";
        }
    }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // 创建并启动子线程
    WorkerThread thread;
    thread.start();

    // 等待子线程完成
    thread.wait();

    return a.exec();
}

#include "main.moc"

代码解释

  1. 启动 QProcess
    • 使用 QProcess 执行 Dependencies.exe 并传递参数。这个程序假设输出为 JSON 格式。
  2. 捕获程序输出
    • 使用 process.readAllStandardOutput() 来捕获程序的标准输出。
  3. JSON 解析
    • 使用 QJsonDocument::fromJson() 将字符串解析为 JSON 文档。
    • 如果输出的 JSON 格式正确,QJsonDocument 将包含 JSON 数据,否则返回一个空文档。
  4. 保存 JSON 数据到文件
    • 使用 QFile 打开 output.json 文件进行写入。
    • 使用 QJsonDocument::toJson(QJsonDocument::Indented) 将 JSON 数据转换为格式化后的字符串,并写入文件。
  5. 输出调试信息
    • 输出原始程序的输出,以帮助调试。

注意事项

  • JSON 格式验证 :使用 QJsonDocument::isNull() 来确保 JSON 格式有效。如果输入数据无效,这部分会做出提示。
  • 文件路径 :确保你有权限写入 output.json 文件。如果路径包含空格或特殊字符,记得转义它们。

总结

通过使用 QProcess 执行外部程序并获取输出后,你可以使用 QJsonDocument 将输出的数据处理为 JSON 格式,并将其写入到文件中。这个过程对处理命令行工具输出的 JSON 数据非常有用,能够方便地存储和进一步处理。

Qt读取JSON文件

在 Qt 中,读取 JSON 文件非常简单,你可以使用 QFile 来打开文件,结合 QJsonDocument 来解析 JSON 数据。下面是一个示例,展示如何读取一个 JSON 文件并处理其中的数据。

示例代码:读取 JSON 文件

cpp 复制代码
#include <QCoreApplication>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // 文件路径
    QString filePath = "output.json";

    // 打开文件
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Failed to open file:" << filePath;
        return -1;
    }

    // 读取文件内容
    QByteArray fileData = file.readAll();
    file.close();

    // 解析 JSON 数据
    QJsonDocument jsonDoc = QJsonDocument::fromJson(fileData);

    // 检查 JSON 是否有效
    if (jsonDoc.isNull()) {
        qDebug() << "Invalid JSON data in file.";
        return -1;
    }

    // 提取 JSON 对象
    if (jsonDoc.isObject()) {
        QJsonObject jsonObject = jsonDoc.object();
        qDebug() << "Parsed JSON object:" << jsonObject;

        // 示例:访问某个字段
        if (jsonObject.contains("key")) {
            QJsonValue value = jsonObject["key"];
            qDebug() << "Value of key:" << value.toString();
        }
    }

    // 如果 JSON 是数组
    if (jsonDoc.isArray()) {
        QJsonArray jsonArray = jsonDoc.array();
        qDebug() << "Parsed JSON array:" << jsonArray;

        // 示例:遍历数组
        for (int i = 0; i < jsonArray.size(); ++i) {
            QJsonValue value = jsonArray[i];
            qDebug() << "Array element" << i << ":" << value.toString();
        }
    }

    return a.exec();
}

代码解释

  1. 打开 JSON 文件
    • 使用 QFile 打开 JSON 文件,QIODevice::ReadOnly 表示以只读模式打开文件。
  2. 读取文件内容
    • 使用 file.readAll() 读取整个文件内容,并将其保存在 QByteArray 中。
  3. 解析 JSON
    • 使用 QJsonDocument::fromJson() 解析 JSON 数据。
    • QJsonDocument 可以是 JSON 对象或数组,使用 jsonDoc.isObject()jsonDoc.isArray() 判断数据的类型。
  4. 提取 JSON 数据
    • 如果是 JSON 对象,使用 jsonDoc.object() 提取对象,并通过键名获取相应的值。
    • 如果是 JSON 数组,使用 jsonDoc.array() 提取数组,并遍历每个元素。
  5. 处理 JSON 数据
    • 你可以根据需要访问特定字段或元素,并对其进行操作。例如,使用 jsonObject["key"] 获取特定键的值。

读取和解析 JSON 数据

假设 output.json 文件内容如下:

json 复制代码
{
    "name": "Qt Application",
    "version": 1.0,
    "features": ["JSON parsing", "File handling"]
}

输出将会是:

复制代码
Parsed JSON object: {"name": "Qt Application", "version": 1.0, "features": ["JSON parsing", "File handling"]}
Value of key: Qt Application

处理 JSON 数组的示例

如果 output.json 内容是一个 JSON 数组,如下所示:

json 复制代码
[
    {"name": "Qt", "version": 6},
    {"name": "QML", "version": 2}
]

程序会遍历并打印数组内容:

复制代码
Parsed JSON array: [{"name": "Qt", "version": 6}, {"name": "QML", "version": 2}]
Array element 0 : {"name": "Qt", "version": 6}
Array element 1 : {"name": "QML", "version": 2}

总结

通过 QFileQJsonDocument,你可以轻松地读取和解析 JSON 文件。根据 JSON 数据的类型(对象或数组),你可以提取数据并进行处理。这对于与外部 JSON 数据交互非常有用。

相关推荐
Scott9999HH2 小时前
【IIoT流量实战】蒸汽管道阀门全关却仍有流量?用 Python 实现涡街信号 FFT 频谱分析与温压全补偿积算网关,深度拆解靠谱的涡街流量计厂家硬核技术标准
开发语言·python
码智社3 小时前
AES加密原理详解及Java实现加解密实战
java·开发语言
AI云海3 小时前
python 列表、元组、集合和字典
开发语言·python
萧瑟余晖4 小时前
JDK 26 新特性详解
java·开发语言
马优晨4 小时前
Freemarker 完整讲解(后端 Java 模板引擎)
java·开发语言·freemarker·freemarker 完整讲解·freemarker模板引擎
人邮异步社区6 小时前
怎么把C语言学到精通?
c语言·开发语言
心平气和量大福大7 小时前
C#-WPF-控件-TextBox 数据绑定
开发语言·c#·wpf
ttwuai7 小时前
Cursor 生成 CRUD 后,Go 后台接口别只测 200:JWT、RBAC 和 tenant_id 怎么验
开发语言·后端·golang
维天说7 小时前
CLI-Switch 2026年3月版历史设计:Hook、TTY 隔离与 JSON 状态
java·服务器·json
এ慕ོ冬℘゜7 小时前
前端基础:什么是时间戳?JS获取时间戳三种方法与实战用途
开发语言·前端·javascript