I'm trying to convert the below CSV formatted data into a JSON object array,
CSV formatted data: apples,oranges,grapes,peach,pineapple
JSON Object Array: {
fruits: [
{
"name": "apples"
},
{
"name": "oranges"
},
{
"name": "grapes"
},
{
"name": "peach"
},
{
"name": "pineapple"
}
]
}
I referred this npm package https://www.npmjs.com/package/csvtojson and this one with stream parser https://github.com/nicolashery/example-stream-parser, but not sure how this may fit with my need.
Can anyone please suggest a way to convert this CSV data to a JSON object array in the format that's been posted.
Solution for the above query (Please refer the below comments section for more details),
var res = {};
res.fruits = 'apples|1,oranges|2,grapes|3,peach|4,pineapple|5'
.split(',').map(function (fruit) { //as did by @Dmitriy Simushev in the below reply
return {
"name": fruit.split('|')[0],
"value": fruit.split('|')[1]
}
});
document.write('<pre>' + JSON.stringify(res, 0, 2) + '</pre>');
You can use plain javascript, with split and map functions
var res = {};
res.fruits = 'apples|1,oranges|2,grapes|3,peach|4,pineapple|5'
.split(',').map(e => ({
"name": e.split('|')[0],
"value": e.split('|')[1]
}));
document.write('<pre>' + JSON.stringify(res, 0, 2) + '</pre>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With