2

When I assign the same value to two different non-existent keys in QJsonObject, I'm getting an unexpected result:

json["first"] = json["second"] = "world!";

As far as I know, this code should add two new keys first and second, both with a value of world!. Instead the first has a value of another element that previously existed in that QJsonObject, while second actually has the right value of world!. When I separate those two assignments:

json["first"]  = "world!";
json["second"] = "world!";

it works correctly, but how does that make a difference?

Actual (chained) output: QJsonObject({"first":"Hello","foo":"Hello","second":"world!"})

Expected (separate) output: QJsonObject({"first":"world!","foo":"Hello","second":"world!"})

Full source code:

#include <QJsonDocument>
#include <QDebug>

int main(int argc, char *argv[])
{
    QJsonObject json {
        {"foo", "Hello"}
    };

    json["first"] = json["second"] = "world!";

    qDebug() << json;

    return 0;
}

Tested on Qt 5.15.2 MinGW 8.1.0 x64 and Qt 6.3.2 MinGW 11.2.0 x64 in both debug and release builds, both on Windows.

rafalk42
  • 21
  • 2

0 Answers0