Reputation: 767
I'm getting a javascript object array. I'm trying to write it to json file by replacing certain params. i don't require comma separated between every object and need to insert a new json object before every existing object. current js object is
[{name:"abc", age:22},
{name:"xyz", age:32,
{name:"lmn", age:23}]
the expected json output file is,
{"index":{}}
{name:"abc", age:22}
{"index":{}}
{name:"xyz", age:32}
{"index":{}}
{name:"lmn", age:23}
My code is
sourceData = data.map((key) => key['_source'])
const strData = JSON.stringify(sourceData);
const newStr = strData.replace("},{", "}\n{");
const newStr2 = newStr.replace(`{"name"`, `{"index" : {}}\n{"name"`);
fs.writeFile('data.json', newStr2, (err) => {
if (err) {
throw err;
}
console.log("JSON data is saved.");
});
But in my output only the first object is changing. I need this to happen my entire output json file. Please help. Thanks
Upvotes: 1
Views: 51
Reputation: 1074335
Note that the result isn't JSON (but it looks like valid JSON-Lines).
I wouldn't try to do string manipulation on the result of JSON.stringify
. JSON is too complex for manipulation with basic regular expressions.
Instead, since you're outputting the contents of the array, handle each array entry separately:
const ws = fs.createWriteStream("data.json");
sourceData = data.map((key) => key['_source'])
for (const entry of sourceData) {
const strData = JSON.stringify(entry);
ws.write(`{"index":{}}\n${strData}\n`);
}
ws.end();
console.log("JSON data is saved.");
Live Example (obviously not writing to a file):
const sourceData = [
{name:"abc", age:22},
{name:"xyz", age:32},
{name:"lmn", age:23}
];
for (const entry of sourceData) {
const strData = JSON.stringify(entry);
console.log(`{"index":{}}\n${strData}`); // Left off the trailing \n because console.log breaks up the lines
}
console.log("JSON data is saved.");
Upvotes: 0
Reputation: 214959
I'd insert dummy objects first and then map stringify
over the result:
array = [
{name: "abc", age: 22},
{name: "xyz", age: 32},
{name: "lmn", age: 23}]
result = array
.flatMap(item => [{index: {}}, item])
.map(x => JSON.stringify(x))
.join('\n')
console.log(result)
// fs.writeFileSync('path/to/file', result)
Upvotes: 2