1

If I have a json String {"k":"v","a":"b"}.

If I convert it into a json Object and then back to String in Java let say using Gson library and store it in some database.

And Also I convert it into json Object and back to String in Python , it is possible that I get the String as {"a":"b","k":"v"} , though json object will be same but now I cannot do a string match as the order is changed.

How can I solve this problem ?

Peter
  • 2,719
  • 4
  • 25
  • 55
  • You could use [`OrderedDict`](http://stackoverflow.com/a/6921760/887828) I think. – Sevanteri Mar 30 '16 at 09:36
  • Why not do the comparison of the objects? – Kennet Mar 30 '16 at 09:39
  • @Kennet , the database supports string comparison only , comparison is not inside JVM or python. – Peter Mar 30 '16 at 09:42
  • @Hacketo, I don't have the luxury to parse the json as , the database does string comparison and it does not support json, I am saving json into database from python as well as java and hence the problem – Peter Mar 30 '16 at 09:43

2 Answers2

1

There is no guarantee that order of json object keys will be same.

Json object is unordered by specefication: http://json.org/

An object is an unordered set of name/value pairs.

If you want some order, you should use json array instead of json object.

An array is an ordered collection of values.

see also: ECMAScript Language Specification

Kirill
  • 7,580
  • 6
  • 44
  • 95
0

Ensure that the keys are always in sorted order when the JSON is serialized to the database. In Python you would write:

json.dumps(obj, sort_keys=True)

With GSON this is harder to do, you may need to use a different library.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89