How to force jsonencode to return floating format
8 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi,
Is there a way to use jsonencode to force some varialble to be floating format, rather than integer?
apiData = struct;
apiData.job_name= "job_rollup: PT BP Creation";
apiData.as_at_date= '2023-05-01';
apiData.DR= 1.000;
string( jsonencode( apiData, 'PrettyPrint', true))
returns
ans =
"{
"job_name": "job_rollup: PT BP Creation",
"ncores": 32,
"as_at_date": "2023-05-01",
"DR": 1
}"
I want the DR to be 1.0, so other API can recognize that it is float and not integer.
Thanks,
0 commentaires
Réponses (2)
Aakash
le 15 Juin 2023
Use the sprintf function to format the value of DR to a string with one decimal place
So change the required line to: apiData.DR = sprintf('%.1f', 1);
0 commentaires
Rik
le 15 Juin 2023
Unfortunately, as you can see in the documentation, customizing the conversion is not really possible this way.
You will either have to adjust the output from jsonencode, or you will have to write your own implementation. Writing your own implementation is not that difficult, especially if you control the input and can therefore implement all paths your code needs to take.
I have written such an implementation, but I will not share it here, precisely because it only does what I need it to do. Once I have written a larger test suite, I may post it on the FileExchange, just like I did with my alternative to jsondecode: JSON. Given the name of this submission I might add the encoder to this submission. If you want to get notified if and when that happens, feel free to click the follow button there.
0 commentaires
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!