Egle
Egle

Reputation: 21

Convert QString to QJsonArray

I am trying to get an array from a QString.

I got advices online to convert the string to QJsonDocument, however, my array is empty.

QString string = "\"person\":\"{\"name\":\"John\", \"surname\":\"Smith\"}";
QJsonDocument doc1 = QJsonDocument::fromJson(string.toUtf8());

QJsonArray array = doc1.array();

Expected result is to get an array of QJsonValues (a QJsonArray):

array[0] : {"name":"John"},
array[1] : {"surname":"Smith"}

Upvotes: 1

Views: 5343

Answers (2)

Rocky
Rocky

Reputation: 86

Try this:

QString string = "{\"person\":{\"name\":\"John\", \"surname\":\"Smith\"}}";

QJsonDocument doc = QJsonDocument::fromJson(string.toUtf8());
QJsonObject json = doc.object();

QJsonArray jsonArray;

foreach(const QString& key, json.keys()) {

        QJsonObject Obj = json.value(key).toObject();

        foreach(const QString& key, Obj.keys()) {

            QJsonObject newObj;
            newObj[key] = Obj.value(key).toString();
            jsonArray.push_back(newObj);

        }
    }

qDebug() << "JSONARRAY" << jsonArray << endl;

// TO ACCESS YOUR ARRAY

for(int i = 0; i<jsonArray.size(); i++) {

    QJsonObject person = jsonArray.at(i).toObject();

    qDebug() << person;
}

OUTPUT:

JSONARRAY QJsonArray([{"name":"John"},{"surname":"Smith"}]) 

QJsonObject({"name":"John"})
QJsonObject({"surname":"Smith"})

But I will suggest you to keep name and surname in one object so you can access and manage it properly like below:

QString string = "{\"person\":{\"name\":\"John\", \"surname\":\"Smith\"}}";

QJsonDocument doc = QJsonDocument::fromJson(string.toUtf8());
QJsonObject json = doc.object();

QJsonArray jsonArray;

foreach(const QString& key, json.keys()) {

        QJsonObject Obj = json.value(key).toObject();
        jsonArray.push_back(Obj);
    }

qDebug() << "JSONARRAY" << jsonArray << endl;

// TO ACCESS YOUR ARRAY

for(int i = 0; i<jsonArray.size(); i++) {

    QJsonObject person = jsonArray.at(i).toObject();

    qDebug() << person << endl;
    qDebug() << "name: " << person.value("name").toString() << endl;
    qDebug() << "surname: "<< person.value("surname").toString() << endl;

}

OUTPUT:

JSONARRAY QJsonArray([{"name":"John","surname":"Smith"}]) 

QJsonObject({"name":"John","surname":"Smith"}) 

name:  "John" 

surname:  "Smith"

Upvotes: 0

Remy Lebeau
Remy Lebeau

Reputation: 595712

There are no arrays present in the JSON string shown.

Arrays are denoted by [ ] characters. Objects are denoted by { } characters.

The JSON you showed, "person":"{"name":"John", "surname":"Smith"}", is malformed because it has too many embedded " characters in it. So lets assume that is just a typo on your part.

"person":{"name":"John", "surname":"Smith"} is a single field named person whose value is an object containing two named string fields, name and surname. QJsonDocument can't parse this as-is, because it is expecting the JSON to be either an object or an array.

{"person":{"name":"John", "surname":"Smith"}} is an unnamed object containing the same kind of person field. doc1.isObject() returns true for this.

Either way, there is no array for doc1.array() to return (doc1.isArray() returns false). So, if you want an array out of this data, you will have to create it yourself, eg:

QString string = "{\"person\":{\"name\":\"John\", \"surname\":\"Smith\"}}";
QJsonDocument doc1 = QJsonDocument::fromJson(string.toUtf8());
if (!doc1.isObject()) {
    // handle parse error...
}

QJsonValue &person = doc1["person"];
if (person.isUndefined()) {
    // key "person" does not exist...
}


// creates an array of strings:
// array[0] = "John"
// array[1] = "Smith"
QJsonArray array = {
    person["name"],
    person["surname"]
};

or

// creates an array of objects:
// array[0] = {"name":"John"}
// array[1] = {"surname":"Smith"}
QJsonArray array = {
    QJsonObject({"name", person["name"]}),
    QJsonObject({"surname", person["surname"]})
};

// use array as needed...

Upvotes: 4

Related Questions