Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What determines the order of returned JSON?

Tags:

swift

vapor

Forgive me if this is not a Swift problem, but at this point I don't know.

My returned JSON looks like this:

[
   {
      "name" : _,
      "age" : _,
      "jobs" : [],
      "gender" : _
   }
]

But my Codable Struct looks like

struct Person: Codable {
   let name: String
   let age: Int
   let gender: String
   let jobs: [Job]
}

Is it random or I did fail to set a parameter or what?

like image 316
Sergio Bost Avatar asked Oct 24 '25 14:10

Sergio Bost


2 Answers

JSON's dictionaries are unordered, as defined by the JSON spec. Even if you produced JSON that has object fields ordered a particular way, no JSON-spec compliant consumer is obligated to respect your orderinging.

Swift's Dictioanry is similarly unordered, and seeded differently on every app launch in order to resist hash collision based DOS attacks.

That being said, there are times when trying to manipulate JSON in an order-sensitive way can be beneficial, even if not required by the spec. Consider the example of a tool that's meant to manipulate JSON files that are version controlled in git.

Most tools work by reading a file's contents, parsing it to a data structure, manipulating the data structure, and then saving it to the file anew. Such a process would cause a small change (like adding/removing a single key) to cause a full rearranging of the entries, changes to unrelated white-space, etc., all of which would blow up the diff.

In cases like that, it's useful to use order-sensitive parsers and collections, which preserve enough information about the original text so as to let you manipulate it in a minimal way.

Of course, the system that consumes these files would ignore the order, as is typical.

like image 129
Alexander Avatar answered Oct 26 '25 04:10

Alexander


You can setup json strings in lexicographic order.If you have a jsonObject, such as data, then you can convert it to json string like this:

let jsonString = JSONSerialization.data(withJSONObject: data,
                                        options: JSONSerialization.WritingOptions.sortedKeys)

when you use sortedKeys option, the json will specify that the output sorts keys in lexicographic order

like image 28
riven Avatar answered Oct 26 '25 05:10

riven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!