1

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

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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.");

2 Comments

the data.json file is empty. FYI i need the exact syntax, though it's not a perfect json file
@MohamedAhkam - I should have been calling end() rather than destroy(). But if you want to build the entire string first and then write it, you can do it georg's way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.