0

How can I format the json output file to format the content like in the example?

[
  {"keyA1": "value1", "keyA2": "value2", "KeyAN": "valueN"},
  {"keyB1": "value1", "keyB2": "value2", "KeyBN": "valueN"},
  {"keyC1": "value1", "keyC2": "value2", "KeyCN": "valueN"},
]

There are a ton of answers like this other answer but this is not how I want it.

EDIT: maybe the question is not clear to everyone. I want the json file to be formated like this, not the javascript.

EDIT 2: this is how I am doing it now:

    const newAdmin = { 
        id: Math.floor(dateNow.getTime() / 1000), 
        firstName: firstName, 
        lastName: lastName, 
        birthDate: new Date(birthDate).toLocaleDateString(),
        registrationDay: dateNow.toLocaleDateString()
    };
    members.push(newAdmin);

    await Deno.writeFile(membersFilePath!, encoder.encode(JSON.stringify(members, null, 1)));
Tinaira
  • 727
  • 2
  • 7
  • 23

2 Answers2

2

You can try mapping through each item individually and stringifying, then joining together by a linebreak:

var arr = [{"keyA1": "value1", "keyA2": "value2", "KeyAN": "valueN"},{"keyB1": "value1", "keyB2": "value2", "KeyBN": "valueN"},{"keyC1": "value1", "keyC2": "value2", "KeyCN": "valueN"},]

const result = "[\n" + arr.map(e => '  ' + JSON.stringify(e)).join(',\n') + "\n]";

console.log(result)
Sourabh Burse
  • 359
  • 2
  • 7
  • I don't know what I am doing wrong but this is the output in the json file: "[\n {\"id\":1670713260,\"user\":\"new user\",\"city\":\"berlin\",\"registrationDay\":\"12/11/2022\"}\n]" – Tinaira Dec 10 '22 at 23:04
  • 1
    This might help you: https://stackoverflow.com/questions/34648904/how-can-i-remove-escape-sequences-from-json-stringify-so-that-its-human-readabl – Sourabh Burse Dec 12 '22 at 20:26
-1

How about a manual way of doing it. Check the code below:

const data = [{"keyA1": "value1", "keyA2": "value2", "KeyAN": "valueN"},{"keyB1": "value1", "keyB2": "value2", "KeyBN": "valueN"},{"keyC1": "value1", "keyC2": "value2", "KeyCN": "valueN"},];

        let json = "[";

        for (const item of data) {
            json += "\n  {";

            for (const key in item) {
                json += `"${key}": "${item[key]}",`;
            }

            json += "},";
        }

        json += "\n]";

        console.log(json);
Feras Wilson
  • 380
  • 1
  • 3
  • 13