Cuadue
Cuadue

Reputation: 3929

Sort a QJsonArray

Suppose I have a function of type:

bool sortJson(QJsonArray &);

which should sort the QJsonArray (and return true) if all members are double. I know I can build an auxiliary QVector, iterate through the QJsonArray and test each element for isDouble(), and append to the QVector, finally sorting the QVector, iterating through it again, and inserting back into the QJsonArray.

Is there a nicer way to convert between QJsonArray and QVector<dobule>? Or, are there short functions with these types?

bool jsonToVector(const QJsonArray&, QVector<double>&);
bool vectorToJson(const QVector<double>&, QJsonArray&);

Upvotes: 2

Views: 1969

Answers (1)

TheDarkKnight
TheDarkKnight

Reputation: 27611

I don't believe there is such a function, but what do you define as an item being a double?

If you have { 0.0, 1, 2.2 }, is that: -

  • a list of {float, int, double}
  • a list of { double, int, double }
  • 3 doubles
  • 3 floats

I would say all may be true, as JSON is just a textual representation. If you just want to check if it can be converted to a double, then you can convert a JsonArray to a QVariantList and check if each item can then be converted to a double

QVariantList varList = jsonArray.toVariantList();
foreach(QVariant item, varList)
{
    bool bOk;
    item.toDouble(&bOk);
    if(bOk)
    {
        // item can be converted to a double
    }
}

Whichever method you choose, I don't believe there's a quick function to sort the json array directly.

Upvotes: 1

Related Questions