JSON.stringify() arguments still returns objects in a straight line with slashes // in between.
I added ```JSON.stringify(stringifiedData, null, 4) to my code to prettify my object. But I am still getting all my data in a straight line with slashes in between.
what I am getting:
"{\"stringifiedData\":\"\\\"{\\\\\\\"collection\\\\\\\":[{\\\\\\\"fruit\\\\\\\":\\\\\\\"apple\\\\\\\",\\\\\\\"clothings\\\\\\\":{\\\\\\\"item\\\\\\\":\\\\\\\"winter\\\\\\\"}},{\\\\\\\"fitness\\\\\\\":\\\\\\\"treadmill\\\\\\\",\\\\\\\"mindfulness\\\\\\\":\\\\\\\"app called calm\\\\\\\"}]}\\\"\"}"
Here's the code:
const fs = require("fs").promises;
async function dataReader(filePath, data) {
const result = await fs.readFile(filePath);
try {
return JSON.parse(result);
} catch (e) {
console.error(e);
}
}
//read values.json
(async () => {
const value = await dataReader("./values.json");
//read collection.json
const data = await dataReader("./collections.json");
//replace tokens in `collection.js` with `values.js`
let stringifiedData = JSON.stringify(data);
Object.keys(value).forEach((token) => {
stringifiedData = stringifiedData.replaceAll(`__${token}__`, value[token])
});
// write/save the new replaced token values in collection.json
await fs.writeFile("./collections.json", JSON.stringify(stringifiedData, null, 4));
})();
collection.json
{
"collection" : [
{
"fruit": "__fruit_type__",
"clothings":{
"item": "__clothing_type__}"
}
},
{
"fitness": "__fitness_equipment__",
"mindfulness": "app called __meditation_app__"
}
]
}
**values.json**
{
"clothing_type": "winter",
"fruit_type": "apple",
"fitness_equipment": "treadmill",
"meditation_app": "calm"
}
expected result:
{
"collection": [
{
"fruit":"apple",
"clothings":{
"item":"winter}"
}
},
{
"fitness":"treadmill",
"mindfulness":"app called calm"
}
]
}