11# ## Serialisation to JSON / string
22
33using JSON: JSON
4+ using OrderedCollections: OrderedDict
45
56# String constants for each index type that we support serialisation /
67# deserialisation of
@@ -70,6 +71,10 @@ then implement the following two methods:
7071 type (perhaps prefixed with module qualifiers) as this value to avoid
7172 clashes. The remainder of the dictionary can have any structure you like.
7273
74+ Note that `Base.Dict` does not guarantee key order, so if you need to preserve
75+ key order for fidelity in serialisation, consider returning an
76+ `OrderedCollections.OrderedDict` instead.
77+
73782. Suppose the value of `index_to_dict(i)["type"]` is `"MyModule.MyIndexType"`.
7479 You should then implement the corresponding method
7580 `AbstractPPL.dict_to_index(::Val{Symbol("MyModule.MyIndexType")}, dict)`,
@@ -119,8 +124,7 @@ function optic_to_dict(i::Index)
119124 # For some reason if you don't do the isempty check, it gets serialised as `{}`
120125 # rather than `[]`
121126 " ix" => isempty (i. ix) ? [] : collect (map (index_to_dict, i. ix)),
122- # TODO (penelopeysm): This is potentially lossy since order is not guaranteed
123- " kw" => Dict (String (x) => index_to_dict (y) for (x, y) in pairs (i. kw)),
127+ " kw" => OrderedDict (String (x) => index_to_dict (y) for (x, y) in pairs (i. kw)),
124128 " child" => optic_to_dict (i. child),
125129 )
126130end
@@ -144,7 +148,7 @@ function varname_to_dict(vn::VarName)
144148 return Dict (" sym" => getsym (vn), " optic" => optic_to_dict (getoptic (vn)))
145149end
146150
147- function dict_to_varname (dict:: Dict {<:AbstractString,Any} )
151+ function dict_to_varname (dict:: AbstractDict {<:AbstractString,Any} )
148152 return VarName {Symbol(dict["sym"])} (dict_to_optic (dict[" optic" ]))
149153end
150154
@@ -178,4 +182,4 @@ Convert a string representation of a `VarName` back to a `VarName`. The string
178182should have been generated by `varname_to_string`.
179183"""
180184string_to_varname (str:: AbstractString ) =
181- dict_to_varname (JSON. parse (str; dicttype= Dict {String,Any}))
185+ dict_to_varname (JSON. parse (str; dicttype= OrderedDict {String,Any}))
0 commit comments