QJsonObject comparison
-
So, I have two objects of same length and order and I want to compare the values in my object using keys. I have written a rough code and I would like to know if it works or is there any other way that this could be done.
I cannot use the qjsonobject equality method because even though the order and the keys are the same, the values might vary and I wish to point that difference out by iterating through my objects.if(bool(refobject.length()==testobject.length())==true) { QJsonObject::iterator i,j; for (i = refobject.begin(), j= testobject.begin(); i!=refobject.end()&&j!=testobject.end(); ++i,++j) { if(i.key()==j.key()) { if(i.value().isString() && j.value().isString()) { if(i.value()==j.value()) { //display i and j } else { //display them in a different colour } } else if(i.value().isArray()&& j.value().isArray()) { //iterate and compare } else if(i.value().isObject() && j.value().isObject()) { //check if there are strings or integers or array and work accordingly } else if(i.value().isDouble() && j.value().isDouble()) { if(i.value()==j.value()) { //display i and j } else { //display them in a different colour } } } } } else{//display message that you cannot compare them} } }
-
@rosh7
In principle your iteration algorithm looks OK. Since you do not alter either object you could use https://doc.qt.io/qt-5/qjsonobject-const-iterator.html instead ofQJsonObject::iterator
, to maybe gain an extra mark :)In your
isObject()
case, and also in yourisArray()
case where you note you will need to iterate and compare, you will need to call this function again recursively if you encounter anisObject()
(i.e. aQJsonObject
). In your other post, you showed your input file, and IIRC it had JSON objects and/or arrays at the top level(s), not only at the bottom, leaf levels. So the recursion will be needed to walk down the tree.