c++qtqt5qjsonobject

How to merge two QJsonObjects in Qt?


I have:

QJsonObject obj1({"bla" : "lab"})
QJsonObject obj2({"bla2" : "lab2"})

and I need:

QJsonObject obj3({"bla" : "lab", "bla2" : "lab2"})

Or in JSON:

{
    "bla" : "lab"
}

{
    "bla2" : "lab2"
}

And I need:

{
    "bla" : "lab",
    "bla2" : "lab2"
}

How to achieve that?


Solution

  • Solution

    I prefer to avoid explicit loops, so my solution would be to use a convertion to and from QVariantMap, aka QMap<QString, QVariant>:

    1. Use QJsonObject::toVariantMap to convert all JSON objects to QVariantMap

    2. Use QMap::insert to insert all maps into one

    3. Use QJsonObject::fromVariantMap to convert the resulting map back to JSON object

    Note: The proposed solution would work best if all JSON objects contain unique keys, because the documentation states:

    If map contains multiple entries with the same key then the final value of the key is undefined.

    Example

    Here is a simple example I have prepared for you to demonstrate how the proposed solution could be implemented:

    QJsonObject json1{{"foo_key", "foo_value"}};
    QJsonObject json2{{"moo_key", "moo_value"}, {"boo_key", "boo_value"}};
    QVariantMap map = json1.toVariantMap();
    
    map.insert(json2.toVariantMap());
    
    qDebug() << QJsonObject::fromVariantMap(map);
    

    Result

    This example produces the following result:

    QJsonObject({"boo_key":"boo_value","foo_key":"foo_value","moo_key":"moo_value"})