I have this JSON file:
{
"weight": 12.0,
"values": [
23.4,
16.5,
16.8,
5.0,
0.0,
0.0,
0.0
]
}
If I trying to read this file and then write it back (using JSON.parse and JSON.stringify)
const fs = require('fs')
const json = JSON.parse(fs.readFileSync('test.json'))
console.log(json)
fs.writeFile('test2.json', JSON.stringify(json), (error) => {
if (error) console.log(error)
})
The output file looks like this:
{
"weight": 12,
"values": [
23.4,
16.5,
16.8,
5,
0,
0,
0
]
}
The problem is if float values ends with .0.
But I need keep these values as in the original.
Can I somehow read float value like a string, and then write it like float value
(even if it ends with .0)?
P.S. Node.js v7.7.4
For each of them you can use the modulus operator (%) to determine if it's a whole number, and if so convert it to a string and append ".0" to the end of it:
json.values.map(v => {
return v % 1 === 0 ? v + ".0" : v
})
var json = {
"weight": 12.0,
"values": [
23.4,
16.5,
16.8,
5.0,
0.0,
0.0,
0.0
]
}
var result = json.values.map(v => {
return v % 1 === 0 ? v + ".0" : v
})
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With