Qt Parse of a Json (object within an array)

2

I have the next json

{
   "Perfiles":   [{

        "Nombre":"Default",
        "E/S": {
            "EntradaHr": 6.45,
            "SalidaHr": 12.15
        }

    }] 
}

And the following code

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

int main(int argc, char *argv[]){
    QFile jsonFile("miJson.json");
    jsonFile.open(QIODevice::ReadOnly | QIODevice::Text);
    QByteArray jsonFileData = jsonFile.readAll();
    jsonFile.close();

    QJsonDocument document = QJsonDocument::fromJson(jsonFileData);
    QJsonObject object = document.object();

    QJsonValue value = object.value("Perfiles");
    qDebug() << "Value => " << value;

    QJsonArray array = value.toArray();
    qDebug() << "Array => " << array;

    QJsonObject e_sObj = object["E/S"].toObject();
    qDebug() << "E/s Object => " << e_sObj;
    qDebug() << "Object value => " << object.value("E/S");

    auto entradaHr = e_sObj["EntradaHr"];
    qDebug() << "Hora entrada => " << entradaHr;

    return 0;
}

I can not access object E/S

    "E/S": {
        "EntradaHr": 6.45,
        "SalidaHr": 12.15
    }

My question is how could I access it?

    
asked by user9139791 04.05.2018 в 02:50
source

1 answer

2

You are not understanding the structure of JSON:

{
   "Perfiles":   [{

        "Nombre":"Default",
        "E/S": {
            "EntradaHr": 6.45,
            "SalidaHr": 12.15
        }

    }] 
}

In JSON, arrays are delimited with brackets [] and objects with braces {} . In this case, Perfiles is a array of objects , so it has a key inside the brackets. You are skipping this entire structure and try to access E/S as if the key was at the height of Perfiles :

QJsonObject object = document.object(); // object es el objeto raiz

QJsonValue value = object.value("Perfiles"); // Recuperas la clave Perfiles
qDebug() << "Value => " << value;

QJsonArray array = value.toArray();
qDebug() << "Array => " << array;

QJsonObject e_sObj = object["E/S"].toObject(); // E/S tambien en el raiz????

As I mentioned, you have to convert the first element of the array into an object and then inspect the object:

QJsonObject primerPerfil = array.at(0).toObject();
QJsonObject e_sObj = primerPerfil.value("E/S").toObject();

Once this is done, to recover the input and output values, we must act on e_sObj , not on objeto (which we remember represents the root of the JSON):

qDebug() << "Entrada => " << e_sObj.value("EntradaHr").toDouble();
qDebug() << "Salida  => " << e_sObj.value("SalidaHr").toDouble();
    
answered by 04.05.2018 / 07:34
source