Reputation: 89
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
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
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
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
Reputation: 1535
Upvotes: 0