【问题标题】:How to append json data into existing json file in Qt如何将 json 数据附加到 Qt 中的现有 json 文件中
【发布时间】:2020-01-14 18:04:14
【问题描述】:

我正在创建 .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 文件

【问题讨论】:

  • 您不应在 json 文件的末尾附加任何内容,因为在根对象之外添加其他内容不是有效的 json 格式。您应该将其加载到正确的QJsonDocument 中,根据需要对其进行编辑并将其写回文件中。
  • 如何编辑 QJsonDocumnet ?用于附加数据

标签: c++ json qt


【解决方案1】:

您应该加载整个 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;
}

【讨论】:

    【解决方案2】:

    您也应该以附加模式打开文件:(QIODevice::Append)

    myFile.open(QIODevice::WriteOnly | ... | QIODevice::Append)
    

    【讨论】:

    • 我在 QIODevice::Append 模式下打开文件,文件写入成功,但读取时我没有得到任何输出“加载 JSON 时出错:“文档末尾有垃圾”@ 548”
    猜你喜欢
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 2018-07-04
    • 2012-10-11
    相关资源
    最近更新 更多