How to get jsondecode to preserve map keys (numerical keys are prefixed with 'x')
18 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Antti Alakiikonen
el 14 de Feb. de 2020
Comentada: Antti Alakiikonen
el 9 de Jul. de 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 comentarios
Respuesta aceptada
Jemima Pulipati
el 23 de Dic. de 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:
Más respuestas (0)
Ver también
Categorías
Más información sobre JSON Format en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!