QJsonObject isUndefined is never undefined when applied to a copy
-
I use Json files for initialisation of my program. Some variables are predefined by default, so if a certain tag is not in the init file I want to use these.
Now, if I use QJsonObject init["sometag"].isUndefined() to check for existence of an initialisation value, this works if init is the original object.
But after QJsonObject copy = init;
copy["sometag"],isUndefined() returns always false, and "sometag": Null is inserted into copy.
Same happens with
QJsonObject subpart = init["subpart"]Is this a bug or a feature, and how can I work around this?
Uli
-
@lurchi
isUndefined()
does something different from what you are thinking it does.You cannot index ause bool QJsonObject::contains(const QString &key) const to check whether a key exists before trying to index by it.QJsonObject
by["some arbitrary string"]
, so it won't get as far as the followingisUndefined()
.EDIT
I realise this contradicts https://doc.qt.io/qt-5/qjsonobject.html#operator-5b-5dThe returned QJsonValue is QJsonValue::Undefined if the key does not exist.
and you are asking a question about behaviour after copying via
QJsonObject copy = init;
being different, is that right? I am rethinking.....EDIT2
OK, if I understand right, your issue is going to be connected to this method: QJsonValueRef QJsonObject::operator[](const QString &key)Returns a reference to the value for key. If there is no value with key key in the object, one is created with a QJsonValue::Null value and then returned.
Now, I think you will find that you calling
init["sometag"].isUndefined()
activates this.
init["sometag"]
had no such key initially, but executing this creates one withQJsonValue::Null
value in theinit
object. (Verify that for yourself before versus after the call by usingcontains("sometag")
.) And then that gets copied tocopy
....Think about using what I said above about
QJsonObject::contains(const QString &key)
to avoid creating the non-existent key-value.P.S.
If I am not mistaken: you have an initialQJsonObject
,init
. If you never wish to modify it and only make changes incopy
try to declareinit
(or something referring to it) asconst
. That way should prevent you (compiler) callinginit["sometag"]
and having it create that key ininit
as an unwanted side-effect --- only the variousconst
overrides ofQJsonObject::operator[]
etc. will be allowed?