How to force jsonencode to return floating format
14 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (2)
Aakash
el 15 de Jun. de 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 comentarios
Rik
el 15 de Jun. de 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 comentarios
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!