How to get jsondecode to preserve map keys (numerical keys are prefixed with 'x')

16 次查看(过去 30 天)
Hi,
Could someone explain why this happens:
jsonencode(jsondecode('{"a":"b"}'))
% '{"a":"b"}' (works as one would assume)
jsonencode(jsondecode('{"1":"b"}'))
% '{"x1":"b"}' (numeric value is previxed with 'x')
jsonencode(jsondecode('{"a.b":"b"}'))
% '{"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)
Thanks

采纳的回答

Jemima Pulipati
Jemima Pulipati 2020-12-23
Hello,
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:

更多回答(0 个)

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by