首页 > 解决方案 > 如何将 json 数据附加到 Qt 中的现有 json 文件中

问题描述

我正在创建 .json 文件,并且正在尝试将新数据附加到 json 文件中。为此,我调用附加文件而不是 writeonly 文件,但在控制台“加载 JSON 时出错:”文档末尾的垃圾“@ 548”如何附加 json 文件?

/*-------------Write data into files ------------*/
void addLogs(QString flightType, QString flightTextLogs){
QFile file("FlightNotifications.json"); // json file
file.open(QFile::WriteOnly ); // Append
QJsonObject m_projectDetails;

qint64 qiTimestamp=QDateTime::currentMSecsSinceEpoch();
QDateTime dt;
dt.setTime_t(qiTimestamp/1000);
m_projectDetails.insert("Type", flightType);
m_projectDetails.insert("TextLog", flightTextLogs);
m_projectDetails.insert("Date and Time",dt.toString("yyyy-MM-dd hh:mm:ss"));

rootObject.insert("Notifications",m_projectDetails);

rootObject1.append(rootObject);
QJsonDocument doc1(rootObject1);
file.write(doc1.toJson());
file.close();
}


 /*--------------- Read json file-----------------*/
 void readFlightLogs(){
qDebug()<<"Read data";
QByteArray val;
QFile file("FlightNotifications.json");
if(file.exists())
{
    file.open(QIODevice:: ReadOnly | QIODevice::Text);
    val = file.readAll();
    file.close();

     QJsonParseError jspe{};
    const QJsonDocument doc = QJsonDocument::fromJson(val, &jspe);
     if (doc.isNull())
    {
        qWarning() << "Error loading JSON:" << jspe.errorString() << "@" << jspe.offset;

    }
    QJsonArray jsonArray = doc.array();

    if(jsonArray.size()<1)
    {
    }
    for (int i=0; i < jsonArray.size(); i++)
    {
      QJsonObject temp = jsonArray.at(i).toObject();
      FlightNotificationList ::getInstance()-> addAsset(temp.value("Notifications").toObject().value("Type").toString(),
                        temp.value("Notifications").toObject().value("TextLog").toString(),
                         temp.value("Notifications").toObject().value("Date and Time").toString(),
                        "name");
       qDebug() << temp.value("Notifications").toObject().value("Type").toString();
       qDebug() <<  temp.value("Notifications").toObject().value("TextLog").toString();
       qDebug() <<  temp.value("Notifications").toObject().value("Date and Time").toString();
  }
}
}

当我使用 QFile::WriteOnly 文件被覆盖。如何附加 .json 文件

标签: c++jsonqt

解决方案


您应该加载整个 json 数组内容,插入新项目,然后将 json 数组重写到磁盘。

addLogs函数可以重写为:

/*-------------Write data into files ------------*/
bool addLogs(QString flightType, QString flightTextLogs){

    QFile file("FlightNotifications.json"); // json file
    if( !file.open( QIODevice::ReadOnly ) ) //read json content
    {
        //open file error ...
        return false;
    }

    QJsonDocument jsonOrg = QJsonDocument::fromJson( file.readAll() );
    file.close();

    //local variable, do not use m_ prefix.
    QJsonObject projectDetails = { {"Type", flightType},
                                   {"TextLog", flightTextLogs},
                                   {"Date and Time", QDateTime::currentDateTime().toString( "yyyy-MM-dd hh:mm:ss" )} };

    QJsonObject notificationObj =  {{ "Notifications", projectDetails }};

    QJsonArray arrLog = jsonOrg.array();
    arrLog.push_back( notificationObj );

    QJsonDocument doc( arrLog );

    if( !file.open( QIODevice::WriteOnly ) ) //write json content to file.
    {
        //cannot open for write ...
        return false;
    }

    file.write(doc.toJson());
    file.close();

    return true;
}

推荐阅读