Home > Software design >  How can I save JSON to local text file in QT?
How can I save JSON to local text file in QT?

Time:10-19

jsonlist.push(Object.assign(process1_json,process2_json,process3_json,process4_json,process5_json, process6_json))

var j = JSON.stringify(jsonlist);

Project Structure

I can use console.log to get JSON output, but I want to generate a local JSON file.

It seems like JavaScript cannot read/write local files directly, so if I have to convert JSON to QJson then get a local JSON file?

CodePudding user response:

You could do it by converting your JSON to a QJsonObject in C , and then save it with that function :

bool writeJson(const QString &fileName, const QJsonObject &object)
{
   //open file
   QFile file(fileName);
   if(!file.open(QIODevice::WriteOnly | QIODevice::Text)){
       qDebug() << QString("Fail to open the file:" fileName);
       return false;
   }

   //convert to document
   QJsonDocument d = QJsonDocument(object);
   //write and close
   file.write(d.toJson());
   file.close();
   return true;
}

CodePudding user response:

Thank you anyway. I have solved it by introducing C module.

#ifndef FILECONTENT_H
#define FILECONTENT_H

#include <QObject>
#include <QFile>
#include <QTextStream>

class FileContent : public QObject
{
    Q_OBJECT
public:
    Q_PROPERTY(QString content READ getContent WRITE setContent)
    Q_PROPERTY(QString filename READ getFileName WRITE setFileName)
    Q_PROPERTY(QString dir READ getDir WRITE setDir)
    Q_INVOKABLE QString getContent();
    Q_INVOKABLE void setContent(QString s);
    Q_INVOKABLE QString getFileName();
    Q_INVOKABLE QString getDir();
    Q_INVOKABLE void setDir(QString s);
    FileContent(QObject *parent = 0);
    ~FileContent();
private:
    QFile   *file;
    QString content;
    QString filename;
    QString dir;
public slots:
    void setFileName(const QString& filename);
    void clearContent();
};

#endif // FILECONTENT_H
#include "filecontent.h"
#include <QDebug>

FileContent::FileContent(QObject *parent) {

}

FileContent::~FileContent() {
    delete file;
}

QString FileContent::getFileName() {
    return this->filename;
}

QString FileContent::getDir()
{
//I need to get file from specific directory path 
    QString envVarName_equip = "MPCVD_MODEL";
    this->dir=qEnvironmentVariable(envVarName_equip.toStdString().c_str());
    return dir  '\\';
}

void FileContent::setDir(QString s)
{
    file = new QFile(s);
}

void FileContent::setFileName(const QString &filename) {
    this->filename = filename;

    file = new QFile(getDir()   '\\'   filename);

}

QString FileContent::getContent() {

    if( content.length() == 0 ) {
        file->open(QIODevice::ReadOnly | QIODevice::Text);
        QTextStream in(file);
        in.setCodec("UTF-8");//set format here
        content = in.readAll();
        if( content.length() == 0) {
            qDebug() << "[Warning] FileContent: file " << this->filename << "is empty" << endl;
        }
    }
    return content;
}

void FileContent::setContent(QString s)
{

    file->open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream in(file);
    in.setCodec("UTF-8");//set format here
    in<<s;

}

void FileContent::clearContent() {
    content.clear();
}

After register in main.cpp,

qmlRegisterType<FileContent>("test.filecontent", 1, 0, "FileContentItem");

just importing this module,

import test.filecontent 1.0

and using like following:

Button{
            id:genjson
            text: qsTr("generate JSON")
            onClicked: {
                
                fileDialog.processContent(new Date().toLocaleString(Qt.locale(), 'yyyyMMdd') ".mpcvd",CJS.genjson())
            }
        }


FileContentItem {
            id: fileDialog
            filename: "default.mpcvd"
            property bool ready: false

            function processContent(source,content) {


                if( source !== undefined ) {
                    filename = source;
                }

                setContent(content);

                clearContent();  // save memory
            }
        }

  • Related