Node.js sample code to convert to JSON array

Tadashi Shigeoka ·  Fri, January 5, 2018

I needed to convert tabular data from Excel, CSV, Google Spreadsheets, etc. to JSON arrays, so I’ll introduce the code I wrote in Node.js.

Node.js

Below is the Node.js sample code to convert to JSON array.

const jsonArray = [];

const arr = [
  [ 1, 2 ],
  [ 3, 4 ]
];

arr.forEach(function(a){
  let json = {
    "hoge": a[0],
    "fuga": a[1]
  };

  jsonArray.push(json);
});

console.log(`%j`, jsonArray);

JSON output result

[{"hoge":1,"fuga":2},{"hoge":3,"fuga":4}]

It’s output in a single line, so if you need to format it, use tools like pretty-json.

That’s all from the Gemba where I wanted to quickly generate JSON arrays dynamically with Node.js.

References