Why jsonencode with containers.Map doesn't preserve order of key value pairs?

6 views (last 30 days)
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?

Accepted Answer

Walter Roberson
Walter Roberson on 2 May 2017
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.
  2 Comments
Walter Roberson
Walter Roberson on 2 May 2017
original_keys = {'one','two','three'};
original_values = [10,11,12];
aux_keys = num2cell( 1:length(original_keys) );
aux_map = containers.Map( aux_keys, original_keys );
original_map = containers.Map( original_keys, original_values );
retrieved_keys = values( aux_map );
retrieved_values = cellfun(@(S) original_map(S), retrieved_keys, 'uniform', 0);
output = jsonencode(cell2struct( retrieved_values, retrieved_keys, 2 ));

Sign in to comment.

More Answers (1)

Adam
Adam on 28 Apr 2017
I'm not quite sure where jsonencode fits in, but a containers.Map is like a lookup table, it doesn't have an order, as such. When you ask for keys or values they are alphanumeric sorted on the keys.
  2 Comments
Robert Snoeberger
Robert Snoeberger on 28 Apr 2017
That is right, containers.Map doesn't preserve insert order. Based on an example in the doc, the keys method returns the keys in alphabetical order.
jsonencode just uses the keys and values methods.
Example:
>> map = containers.Map({'one','two','three'},[1,2,3]);
>> keys(map)
ans =
1×3 cell array
'one' 'three' 'two'
>> values(map)
ans =
1×3 cell array
[1] [3] [2]
>> jsonencode(map)
ans =
'{"one":1,"three":3,"two":2}'
>>
Abhishek Ballaney
Abhishek Ballaney on 2 May 2017
How to preserve the order as given in input? i want to override alphanumeric order and preserve the input order. Please guide.

Sign in to comment.

Categories

Find more on Data Import and Analysis in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!