skip to Main Content

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

2

Answers


  1. 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)
    Login or Signup to reply.
  2. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search