How to get jsondecode to preserve map keys (numerical keys are prefixed with 'x')
22 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Antti Alakiikonen
le 14 Fév 2020
Commenté : Antti Alakiikonen
le 9 Juil 2021
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
0 commentaires
Réponse acceptée
Jemima Pulipati
le 23 Déc 2020
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:
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur JSON Format dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!