0

I have Written a code to get qbytearray output to Qstring list and then splited it using delimeter ',' , in qt c++

Now i need to added it into Json array

Output I am getting is

"diskinfo": "Node: ASHUTOSH-PC, Description: Local Fixed Disk, FreeSpace: 420842713088, Name: C:, Size  : 499875049472  Node: ASHUTOSH-PC, Description: CD-ROM Disc, FreeSpace: , Name: D:, Size  :   Node: ASHUTOSH-PC, Description: Local Fixed Disk, FreeSpace: 324858568704, Name: E:, Size  : 487687450624  Node: ASHUTOSH-PC, Description: CD-ROM Disc, FreeSpace: 0, Name: F:, Size  : 553459712",

Expected output is

{
  "diskinfo": "Node: ASHUTOSH-PC, Description: Local Fixed Disk, FreeSpace: 420842713088, Name: C:, Size  : 499875049472
              Node: ASHUTOSH-PC, Description: CD-ROM Disc, FreeSpace: , Name: D:, Size  : 
              Node: ASHUTOSH-PC, Description: Local Fixed Disk, FreeSpace: 324858568704, Name: E:, Size  : 487687450624 
             Node: ASHUTOSH-PC, Description: CD-ROM Disc, FreeSpace: 0, Name: F:, Size  : 553459712"
}

Now I need to get Expected output Where Starting with every node It should display in the next line in array? I need to create Json array, Then for eachline , create a json object and then split them insert that in Json object and inser that json object in jsonarray, and return that jsonarray to json . How is this poosible? Can any one help?

Following is the code I have written then after that How to creatr and isert it in Json

QString Utils::getDiskSpace()
{
    static QString diskSpaceCmd ( qgetenv("WINDIR") + 
        "\\system32\\wbem\\wmic logicaldisk get name, freespace, size, description /format:csv");

    QProcess proc;
    QByteArray qba;
    QString out_str;

    proc.start(diskSpaceCmd);

    if(proc.waitForFinished(-1))
    {
        qba = proc.readAllStandardOutput();
        qba = qba.trimmed();
        qba = qba.replace('\r',' ');
        QString myString = qba;

        QStringList myStringList = myString.split("\n");

        QStringList descriptions = myStringList[0].split(",");
        descriptions[0] = descriptions[0].remove(0, 
                             descriptions[0].indexOf(" ") + 1);

        for(int index = 1;index < myStringList.length();index++)
        {
            QStringList data = myStringList[index].split(",");
            QStringList out;
            for(int ind_2 = 0; ind_2 < data.length(); ind_2++)
                out.push_back(descriptions[ind_2] + ": " +data[ind_2]);
            out_str += out.join(", ");
        }
    }

    QString diskSpace(out_str);
    return diskSpace;
}

Pseudo code Written for What ouput I want is

ja = QJsonArray();
for (each line)
{
    QJsonObect oj;
    split("token")
    for (each token in line)
        oj.insert(descriptions, data)

    ja.insert(oj)
}
return ja.toJson

How will I this Implement in my actual code.?

Following is my utils.cpp file

    QString WctUtils::getDiskSpace( )
      {
        static QString diskSpaceCmd ( qgetenv("WINDIR")
                               + "\\system32\\wbem\\wmic logicaldisk get name, freespace, size, description /format:csv");

        QProcess proc;
        QByteArray qba;
        QString out_str;


        proc.start(diskSpaceCmd);

        if(proc.waitForFinished(-1))
         {
            qba = proc.readAllStandardOutput();
            qba = qba.trimmed();
            qba =qba.replace('\r',' ');
            QString myString =qba;

            QStringList myStringList = myString.split("\n");

            QStringList descriptions = myStringList[0].split(",");

            for(int index = 1;index < myStringList.length();index++)
             {
               QStringList data = myStringList[index].split(",");
               QStringList out;
               for(int ind_2 = 0; ind_2 < data.length(); ind_2++)
              out.push_back(descriptions[ind_2] + ": " +data[ind_2]);
               out_str += out.join(", ");
              }


             }

           QString diskSpace(out_str);
           return (diskSpace);
        }

This is where mu Json is inserted

         QJsonObject json;
            if(isRemoteServiceManagerEnabled)
             {
               QLOG_INFO() << "windows service manager web service called to get start time";

               json = JamManager::getServiceStartTimes();
               json.insert(ask::HOST_UPTIME, WctUtils::getLastBootupTime());
               json.insert(ask::DISK_INFO, WctUtils::getDiskSpace());
               json.insert(ask::CPU_USAGE,WctUtils::getcpuUsage());
               json.insert(ask::HOST, QHostInfo::localHostName());
             }

             QJsonDocument replyDoc = QJsonDocument(json);

            aResponse.setHeader(ask::CONTENT_TYPE.toLocal8Bit(),           al::JSON_HEADER.toLocal8Bit());
            aResponse.write(replyDoc.toJson());
           }

}

11
  • Qt is aware of the JSON format. doc.qt.io/qt-5/json.html Commented Feb 3, 2017 at 6:06
  • Can you explain me how do i implement it ? Commented Feb 3, 2017 at 6:08
  • There is a concrete example out there! :) doc.qt.io/qt-5/qtcore-json-savegame-example.html Commented Feb 3, 2017 at 6:16
  • I tried it out , but I am not able to figure it out? can u help me with respect to above example Commented Feb 3, 2017 at 6:50
  • Please specify what you want to do. Do you want convert the data into QByteArray? or save it using the JSON format? If you are trying to save it, you should insert serialize part into your pseudo-code. Commented Feb 3, 2017 at 7:52

2 Answers 2

1

You can modify the following code:

#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QFile>

QStringList infos = {"foo", "foofoo", "foofoofoo"}; // you must change it.

// create a json array and fill it.
QJsonArray arr;
foreach(QString const& info, infos)
    arr.append(info);

// create a object for converting.
QJsonObject obj;
obj["diskinfo"] = arr;

// save it.
QJsonDocument doc(obj);
QFile file("save.json");
if(file.open(QIODevice::WriteOnly))
    file.write(doc.toJson());

The output (save.json):

{
    "diskinfo": [
        "foo",
        "foofoo",
        "foofoofoo"
    ]
}

EDIT: I'll implement the above code in your first code.

void Utils::getDiskSpace(QString filename)
{
    static QString const diskSpaceCmd ( qgetenv("WINDIR") + 
        "\\system32\\wbem\\wmic logicaldisk get name, freespace, size, description /format:csv");

    QProcess proc;
    proc.start(diskSpaceCmd);
    if(proc.waitForFinished(-1))
    {
        QByteArray qba;
        qba = proc.readAllStandardOutput();
        qba = qba.trimmed();
        qba = qba.replace('\r',' ');
        QString myString(qba);

        QStringList myStringList = myString.split("\n");

        QStringList descriptions = myStringList[0].split(",");
        descriptions[0] = descriptions[0].remove(0, 
                             descriptions[0].indexOf(" ") + 1);

        QJsonArray jsarr;
        for(int index = 1;index < myStringList.length();index++)
        {
            QStringList data = myStringList[index].split(",");
            QStringList out;
            for(int ind_2 = 0; ind_2 < data.length(); ind_2++)
                out.push_back(descriptions[ind_2] + ": " +data[ind_2]);
            jsarr.append(out.join(", "));
        }

        // create a object for converting.
        QJsonObject obj;
        obj["diskinfo"] = jsarr;

        // save it.
        QJsonDocument doc(obj);
        QFile file(filename);
        if(file.open(QIODevice::WriteOnly))
            file.write(doc.toJson());
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I tried this out this doesnot work. also my string is not a list it is Qstring
Can you add the code you've tried? Then I'll try to fix it.
I have edited my earlier post and added pseudo code for what output i want? Can U help me with the following?
@cyley What do you mean by "does not work"? If it means you couldn't compile it, you must paste the code not a pseudo code of it.
0

Finally I got the Expected output in QJson array:

      QJsonArray disk_array;
      QStringList myStringList = myString.split("\n");

      QStringList descriptions = myStringList[0].split(",");


      for(int index = 1;index < myStringList.length();index++)
      {
          QStringList data = myStringList[index].split(",");
          QJsonObject obj_disk;
          for(int ind_2 = 0; ind_2 < data.length(); ind_2++)
          {
              obj_disk.insert(descriptions[ind_2],data[ind_2]);
          }
          disk_array.append(obj_disk);
      }


 return (disk_array);

Output obtained in Json Format:

     "diskinfo": [
    {
        "Description": "Local Fixed Disk",
        "FreeSpace": "418491035648",
        "Name": "C:",
        "Node": "ASHUTOSH-PC",
        "Size  ": "499875049472  "
    },
    {
        "Description": "CD-ROM Disc",
        "FreeSpace": "",
        "Name": "D:",
        "Node": "ASHUTOSH-PC",
        "Size  ": "  "
    },
    {
        "Description": "Local Fixed Disk",
        "FreeSpace": "324668514304",
        "Name": "E:",
        "Node": "ASHUTOSH-PC",
        "Size  ": "487687450624  "
    },
    {
        "Description": "CD-ROM Disc",
        "FreeSpace": "0",
        "Name": "F:",
        "Node": "ASHUTOSH-PC",
        "Size  ": "553459712"
    }
],

Comments

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.