Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a method to check if a QJsonObject object contains specific attribute?

there is a QJsonObject

    {
        "a":"...",
        "b":"...",
        "c":"..."
    }

is there a method to check if this object contains "a"?

like image 470
stamaimer Avatar asked Apr 10 '14 14:04

stamaimer


2 Answers

You have a few options, according to the documentation:

  • The most obvious is QJsonObject::contains which returns a bool
  • You can call QJsonObject::find which will return an iterator. If the item isn't found, the return value will be equal to QJsonObject::end Use this if you need an iterator anyways.
  • You can call QJsonObject::value, which will return the value for the key if present, and QJsonValue::Undefined otherwise. You're probably using the value method anyways to get the value for a key, so this will allow you to do one lookup instead of two. It may be tempting to use this for a performance boost, but remember that it will be harder to read and in most cases the performance gain is small enough that it's probably not worth it

All of this came directly from the Qt documentation - my favorite thing about Qt is their fantastic documentation, so I encourage you to make that your first stop when you have questions like these.

like image 89
Elliott Avatar answered Oct 17 '22 15:10

Elliott


Right, so in general, Qt uses the API "contains" for such things. If you take a look at the following places, you will see it yourself:

  • QHash: bool QHash::contains(const Key & key) const

  • QMap: bool QMap::contains(const Key & key) const

  • QStringList: bool QStringList::contains(const QString & str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

  • QString: bool QString::contains(const QString & str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

  • QList: bool QList::contains(const T & value) const

  • QVector: bool QVector::contains(const T & value) const

  • QByteArray: bool QByteArray::contains(const QByteArray & ba) const

Having mentioned all this, you may not be entirely surprised that the requested class have a method called contains as follows:

  • QJsonObject: bool QJsonObject::contains(const QString & key) const
like image 2
lpapp Avatar answered Oct 17 '22 15:10

lpapp