Home > Software engineering >  Why JSON.stringify() don't work correctly
Why JSON.stringify() don't work correctly

Time:10-15

I'm actually creating a JSON file with nodejs but when i use the JSON.stringify. My Json Object work correctly when i print it :

My code

But when i stringify my json object i get that :

What i receive when i print my json object

A big part of my json information don't want to be save i don't know why Here's the code :

What i receive when i print my stringified json object

CodePudding user response:

You are attempting to use a 'sparse array' to store your data. Arrays do not have a clear way to be instantiated with elements at a specified index.

An object (or a Map) would suit your requirements better. To use an object, I modified your 'accounts' initation code that was commented:

// replace this:
dataObj["accounts"] = [];
// with this:
dataObj["accounts"] = {};

The other code you are using (e.g. accessing elements using the square brackets) will work the same. You should probably make the same adjustments to the other arrays you are using.

Sparse arrays can get ugly in some notations if you have large blank spaces (which your UUID methodology would certainly have). An object or a Map will not suffer that shortcoming.

An example of similar code, using objects instead of arrays:

let dataObj = {};
dataObj["accounts"] = {};
let uuid = 'abcdefghij12344';
dataObj["accounts"][uuid] = {}
dataObj["accounts"][uuid]['active'] = true;
dataObj["accounts"][uuid]['someotherval'] = true;
 
console.log(dataObj);
//outputs:

{ accounts: { abcdefghij12344: { active: true, someotherval: true } } }

let stringified = JSON.stringify(dataObj);
console.log(stringified);

// Outputs:
{"accounts":{"abcdefghij12344":{"active":true,"someotherval":true}}}

let parsed = JSON.parse(stringified);
console.log(parsed);

//Outputs:
{ accounts: { abcdefghij12344: { active: true, someotherval: true } } }
  • Related