I'm aware that object's properties are not guaranteed to be stored or read in any particular order.
The problem I have is that it's not up to me to use an object or an array. I already have a big and very nested JSON file like this:
{ "occasion": 23, "mayorstips": { "1": 0, "3": 0, "2": 0...
I only have to do some modifications. This is how I start working with it:
var campaign = JSON.parse(fs.readFileSync(theJSONFile));
for(var plot in plots) {
if(plots.hasOwnProperty(plot)) {
switch(plots[plot].province) {
case 'forest':
...
When I'm done, I just put it back with:
fs.writeFileSync(theJSONFile, JSON.stringify(campaign));
Now, I've noticed two problems with this approach:
- The original spacing format is lost. That original file is just one long line and needs to be one long line so any formatting attempt by the
JSON
library hasn't been helpful. I solved it with a few regex replacements. - Now the "JSON line" file is sorted. So I went from
{ "1": 0, "3": 0, "2": 0
to{ "1": 0, "2": 0, "3": 0
and that turns out to be a big problem. - The float numbers that end in 0's are truncated. This file needs the float numbers to always have six decimals, for example, 34.293800. But when I open it, the number changes to 34.2938!
It's a 35 thousand chars line. It's How can I fix problem #2 and #3? I could do yet another regex replace for #3 but maybe there's something I'm missing.