vibe.d
vibe.d copied to clipboard
Sorting Json struct from vibe.d
I faced a problem with wrong sorting JSON keys. I use mongo db and I need to send a creating user command. vibe-d JSON:
Json a2 = Json([
"createUser": Json(req.form["user"]),
"pwd": Json(req.form["password"]),
"roles": Json([
Json([
"role": Json(req.form["access"]),
"db": Json("3dstore")
])
])
]);
logInfo(a2.toString());
Output:
[main(Wbp2) INF] {"roles":[{"role":"readWrite","db":"3dstore"}],"createUser":"111","pwd":"1"}
std.json:
JSONValue a2 = JSONValue([
"createUser": JSONValue(req.form["user"]),
"pwd": JSONValue(req.form["password"]),
"roles": JSONValue([
JSONValue([
"role": JSONValue(req.form["access"]),
"db": JSONValue("3dstore")
])
])
]);
logInfo(a2.toString());
Output:
[main(vVOX) INF] {"createUser":"111","pwd":"1","roles":[{"db":"3dstore","role":"readWrite"}]}
Therefore I get an error in mongo output: "errmsg" : "no such command: 'roles'". It works with a custom struct but it's an extra code.
JSON object are an unordered set of name/value pairs, according to the specification. It's MongoDB to blame here for relying on the order of name/value pairs in the object, this is not the fault of vibe.d in my opinion and I don't think vibe.d should fix this.
As an additional note: std.json
does not preserve order either. Calling toString(…)
calls toJSON(…)
which happens to sort objects by keys. Since the object you posted in your example is also sorted alphabetically by the key, it accidentally preserves the order of keys in your object. :smiley: