MATLAB: How to get jsondecode to preserve map keys (numerical keys are prefixed with ‘x’)


Could someone explain why this happens:
% '{"a":"b"}' (works as one would assume)
% '{"x1":"b"}' (numeric value is previxed with 'x')
% '{"a_b":"b"}' ('.' is converted to '_')
And how to work around it?
Some context:
I'm utilising a web api endpoint to post data, and it requires the data in similar format that in the second case above. But I'm not able to produce reliably the json payload (the example is a simplification of the actual problem)

Best Answer

From my understanding, you are using jsondecode() to decode an object and then used a jsonencode() to encode it back.
You are trying to decode a JSON object, which gets decoded in MATLAB as a MATLAB struct. A valid field name for struct can start only with letters and can contain letters, digits and underscores.
In this case, the field names ("1", "a.b") being provided are not valid field names for struct so makeValidName function modifies these field names and returns a valid field name when the object is used along with jsondecode(). This has been stated as a limitation for jsondecode() documentation. The makeValidName function constructs valid MATLAB identifiers from input strings, where the field names "1", "a.b" are modified to "x1", "a_b".
The expectation of jsondecode() function is a valid JSON object with valid field names (for struct) should be passed as input.
As a workaround, you may use the containers.Map which returns the map object from the inputs 'keySet' and 'valueSet'. In your case, the 'keySet ' could be the actual field name that you want to store and the struct value can be passed onto the 'valueSet' argument.
The following answer from the community might be of relevance to you: