3

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

1 Answers1

2

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);
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • Now you have strings instead of numbers. That's less float-like than the original. – Quentin Mar 24 '17 at 09:30
  • 1
    Thank you. Now I need to write into the json float values like floats (not strings). It's the second part of my question. – DmitryScaletta Mar 24 '17 at 09:40
  • @DmitryScaletta you can't. The numeric value 0.0 *is* 0. Enter `0.0` in your JavaScript console and it will output `0`. The only way you can get JavaScript to retain the decimal is if you treat it as a string instead. – James Donnelly Mar 24 '17 at 09:42