Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Is there a simpler way of building and modifying a QJsonObject?



  • For example, I would like to build the following json (its a simple one for the sake of the sample, in real life I have to construct much larger objects):

    {
        "person":{
            "salary": {
                "min": 10000,
                "max": 20000
            }
        }
    }
    

    I build this object something like this (there might be syntax errors, I did not check):

    QJsonObject({{"person", QJsonObject({{"salary", QJsonObject({{"min", 10000}, {"max", 20000}})}})}})
    

    It can get quite ugly. Is there a better way of constructing such JsonOBject? The min/max values I obtain them dynamically at run time, so they cannot be imported with QJsonDocument::fromJson just like that.


  • Qt Champions 2019

    @need4openid Depending on your exact use case you can read JSON from a string.


  • Lifetime Qt Champion

    Hi,

    Depending on what you would like to do you might also want to consider nlohmann's json library which is quite good.


  • Lifetime Qt Champion

    Hi
    if you are using a c++ 11 compiler you can also use raw string literals.

     QString jsontemplate = R"(
        {
            "person":{
                "salary": {
                    "min": %1,
                    "max": %2
                }
            }
        })";
    
     QString finaleJson = jsontemplate.arg(1000).arg(2000);
    
     qDebug() << finaleJson;
    
    

    ps. +5 for nlohmann's json. Its awesome.


  • Qt Champions 2019

    @need4openid said in Is there a simpler way of building and modifying a QJsonObject?:

    QJsonObject({{"person", QJsonObject({{"salary", QJsonObject({{"min", 10000}, {"max", 20000}})}})}})

    QJsonValue Foo::getValues() const
    {
      return {{"person", m_person},
              {"salary", m_salary},
              {"min", m_min},
              {"max", m_max},
             }
    


  • I like to use the insert method.

        QJsonObject person;
        person.insert("min",10000);
        person.insert("max",20000);
        QJsonObject object;
        object.insert("person",person);
    
        QJsonDocument doc;
        doc.setObject(object);
        qDebug() << doc.toJson(QJsonDocument::Compact);
    


  • If it is more convenient for you to manage the data in a collection (map or hash table), there are methods to create QJsonObject from QVariantMap and QVaraintHash.

    int min = 10000, max = 20000;
    
    QVariantMap salary;
    salary["max"] = max;
    salary["min"] = min;
    
    QVariantMap person;
    person["salary"] = salary;
    
    QVariantMap jsonMap;
    jsonMap["person"] = person;
    
    QJsonDocument jsonDoc(QJsonObject::fromVariantMap(jsonMap));
    qDebug() << jsonDoc.toJson(QJsonDocument::Compact);
    

Log in to reply