Home > Blockchain >  Format json output programatically in javascript/typescript
Format json output programatically in javascript/typescript

Time:12-11

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.

CodePudding user response:

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)

CodePudding user response:

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

  • Related