MATLAB: Jsonencode with containers.Map doesn’t preserve order of key value pairs

jsonencode

Why jsonencode with containers.Map doesn't preserve order of key value pairs? If i give input as A:1,B:2,C:3, output is random like C:3,A:1,B:2. Key value pairs are correct, but their order isn't preserved. How to preserve the order as given in input?

Best Answer

In the special case where all of the keys are valid variable names, you can convert the Map into a struct with field names in the order you desire; jsonencode() of the struct will then be the same as jsonencode of the Map except that you controlled the order.
containers.Map does have any idea what the right order is, and there is no way to force a particular ordering inside the Map. However, you can create another Map between an ordinal and associate key at the time you build the other Map; then you can values() the second Map to find the order to extract the values from the primary Map. You might want to use cell2struct to build the struct to pass to jsonencode.