1

I am creating .json file and I'm trying to append new data into json file. For that I call append file instead of writeonly file but get error at console "Error loading JSON: "garbage at the end of the document" @ 548" How to append json file?

/*-------------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();
  }
}
}

When I use QFile::WriteOnly the file gets override. How to append .json file

3
  • Please read the QFile::Open documentation and follow the link to the QIODevice::OpenMode documentation. Commented Jan 14, 2020 at 9:09
  • 1
    You should not append anything to the end of the json file because it is not valid json format to add others things outside of the root object. You should load it in a proper QJsonDocument, edit it as you need and write it back to the file. Commented Jan 14, 2020 at 9:18
  • how can I edit QJsonDocumnet ? for appending data Commented Jan 14, 2020 at 9:21

2 Answers 2

1

You should load the whole json array content, insert new item then rewrite the json array to disk.

The addLogs function could be rewritten as :

/*-------------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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

you should open the file in append mode too: (QIODevice::Append)

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

1 Comment

I open the file in QIODevice::Append mode file write successfully but for read I didn't get any output instead " Error loading JSON: "garbage at the end of the document" @ 548"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.