How to set Json object to Json document without sorting the keys alphabetically
-
wrote on 29 Jan 2015, 07:57 last edited by
I insert some keys and vals to my Json object like this: @jObj.insert(keyName, val);@
After inserting some key and val pairs to my object I am trying to set the object to Json document with: "void QJsonDocument::setObject(const QJsonObject & object)":http://doc-snapshot.qt-project.org/qt5-5.4/qjsondocument.html#setObject
However this method sorts the keys alphabetically and than puts them into Json document. But I need an unsorted Json document .
-
a simple question: why? :)
I am asking because it's not specified by the JSON standard that the input order should be the same like the output order. And for applications using the JSON data it also doesn't make a difference how the order is.
-
wrote on 29 Jan 2015, 08:06 last edited by
Because I have a database with lots of columns on server side and I want to bind the values in a for loop easily that I got from the client and insert them into server database. Also I want to show the Json document exactly like my database. So I need the same order in database.
-
[quote author="flopoe" date="1422518779"]Because I have a database with lots of columns on server side and I want to bind the values in a for loop easily that I got from the client and insert them into server database.
[/quote]But this is a matter how you design your for loop. For example you can do this with no problem:
@
foreach( QString key, myJsonObject->keys() ) {
// pseudo code
dbQuery.updateColumn( key, myJsonOject.value(key) );
}
@So the database query also isn't dependent of the order actually.
[quote author="flopoe" date="1422518779"]
Also I want to show the Json document exactly like my database. So I need the same order in database.[/quote]Again, for what purpose? It is simply not possible to guarantee this because of the internal data structures used in the Qt implementation. Most probably because of performance reason and because there is just no use case where this is mandatory.
-
wrote on 29 Jan 2015, 08:35 last edited by
Yes I know there are many ways to do it using different methods but I've just wondered this. Thank you!
-
wrote on 29 Jan 2015, 10:47 last edited by
It is quite simple. A JSON object is like a map: a set of keys referencing values, with no inherent order. If you need a specific order, you should not use an object, but a list (of objects).
4/6