How to Convert CSV to JSON (Object Array) in Node.js
There’s no need to waste time searching for complex ways to convert between CSV and JSON; there’s an API for that. The below Node.js code will perform this common data conversion in a matter of seconds.
Simply put, this API will convert CSV file inputs into JSON Object Arrays, all while providing the option to specify if the first row of your CSV data should be used as labels for your columns in the conversion (default is true; set to false if your file has an irregular column structure).
First, run the below command to install the SDK:
npm install cloudmersive-convert-api-client --save
To install a different way, you can add this snippet to your package.json instead:
"dependencies": {
"cloudmersive-convert-api-client": "^2.6.3"
}
Last, copy in the below code to call the function. This stage requires a Cloudmersive API key, which you can get for free (by registering a free account on our website):
var CloudmersiveConvertApiClient = require('cloudmersive-convert-api-client');
var defaultClient = CloudmersiveConvertApiClient.ApiClient.instance;
// Configure API key authorization: Apikey
var Apikey = defaultClient.authentications['Apikey'];
Apikey.apiKey = 'YOUR API KEY';
var apiInstance = new CloudmersiveConvertApiClient.ConvertDataApi();
var inputFile = Buffer.from(fs.readFileSync("C:\\temp\\inputfile").buffer); // File | Input file to perform the operation on.
var opts = {
'columnNamesFromFirstRow': true // Boolean | Optional; If true, the first row will be used as the labels for the columns; if false, columns will be named Column0, Column1, etc. Default is true. Set to false if you are not using column headings, or have an irregular column structure.
};
var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.convertDataCsvToJson(inputFile, opts, callback);
That’s all there is to it — you can put your CSV to JSON conversion needs to rest.