Как добавить данные json в существующий файл json в Qt - PullRequest
1 голос
/ 14 января 2020

Я создаю файл. json и пытаюсь добавить новые данные в файл json. Для этого я вызываю файл добавления вместо файла только для записи, но получаю сообщение об ошибке на консоли «Ошибка загрузки 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 файл

Ответы [ 2 ]

1 голос
/ 14 января 2020

Вы должны загрузить весь массив массива 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;
}
0 голосов
/ 14 января 2020

Вы также должны открыть файл в режиме добавления: (QIODevice :: Append)

myFile.open(QIODevice::WriteOnly | ... | QIODevice::Append)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...