Bramhani G
Bramhani G

Reputation: 89

Node.js convert csv file to json formate

I am beginner to programming. I am reading the csv data from the file then I need to convert csv data into json formate. This is my csv data file:

batch_id  ingredient_code   quantity    expiry_date
1             item1           1000      18-01-2019
1             item2           500       18-02-2019
2             item1           1000      18-01-2019
3             item2           1000      18-08-2019
4             item2           1000      18-01-2019
4             item1           1000      18-05-2019
4             item3           500       18-04-2019
5             item4           1000      18-01-2019

I am expecting output like this

[{
   batch_id : 1,
   items :[{ingredient_code:item1, quantity:1000, expiry_date:18-01-2019},
           {ingredient_code:item2, quantity:500, expiry_date:18-02-2019}]     
   },
   {
     batch_id : 2,
     items :[{ingredient_code:item1, quantity:1000, expiry_date:18-01-2019}]     
    },
    {
      batch_id : 3,
      items :[{ingredient_code:item1, quantity:1000, expiry_date:18-01-2019}]     
    },
    {
      batch_id : 4,
      items :[{ingredient_code:item1, quantity:1000, expiry_date:18-05-2019},
              {ingredient_code:item2, quantity:1000, expiry_date:18-01-2019},
              {ingredient_code:item3, quantity:500, expiry_date:18-04-2019}]     
     },
    {
      batch_id : 5,
      items :[{ingredient_code:item4, quantity:1000, expiry_date:18-01-2019}]     
}]

what I am expecting is batch id should display single time, all the items of that batch id should be added to array. thanks in advance..... sorry for poor english

Upvotes: 1

Views: 7184

Answers (4)

hongkongbboy
hongkongbboy

Reputation: 310

2 Steps Process:

1) Run npm i -g csvtojson in terminal.

2) Run csvtojson source.csv > converted.json in terminal where your file located. Note that "source.csv" is the file that you want to convert and "converted.json" is the file that you will generate.

For documentation, see here

Upvotes: 0

Saniya syed qureshi
Saniya syed qureshi

Reputation: 3177

You can acheive it by installing the csvtojson in your node module, by typing the following command:

npm install csvtojson --save

You can get more detailed information here from-csv-file-to-json-array.

Upvotes: 0

Anusha kurra
Anusha kurra

Reputation: 480

Csv file is in same location as js file,Install node module csvtojson

var csv = require("csvtojson");
csv().fromFile('a.csv').on("json",function(jsonArrayObj){ 
     console.log(jsonArrayObj); 
   })

Upvotes: 2

Krrish Raj
Krrish Raj

Reputation: 1535

  1. Create an empty map.
  2. Iterate over data line by line.
  3. Split each line by comma.
  4. Use batch id as key and look for it in map, it exists, push data into array otherwise initialize that key with an array containing data for that row.
  5. Iterate over keys and create an array out of it.

Upvotes: 0

Related Questions