The below should work for you.
All credit to Convert CSV to JSON in JavaScript (archived), by iwek:
//var csv is the CSV file with headers function csvJSON(csv){ var lines=csv.split("\n"); var result = []; var headers=lines[0].split(","); for(var i=1;i<lines.length;i++){ var obj = {}; var currentline=lines[i].split(","); for(var j=0;j<headers.length;j++){ obj[headers[j]] = currentline[j]; } result.push(obj); } //return result; //JavaScript object return JSON.stringify(result); //JSON }
If your columns contain commas in their values, you'll need to deal with those before doing the next step (you might convert them to &&& or something, then covert them back later).
Answer from Wesley Smith on Stack OverflowThe below should work for you.
All credit to Convert CSV to JSON in JavaScript (archived), by iwek:
//var csv is the CSV file with headers function csvJSON(csv){ var lines=csv.split("\n"); var result = []; var headers=lines[0].split(","); for(var i=1;i<lines.length;i++){ var obj = {}; var currentline=lines[i].split(","); for(var j=0;j<headers.length;j++){ obj[headers[j]] = currentline[j]; } result.push(obj); } //return result; //JavaScript object return JSON.stringify(result); //JSON }
If your columns contain commas in their values, you'll need to deal with those before doing the next step (you might convert them to &&& or something, then covert them back later).
I would check out PapaParse. They have a file called papaparse.min.js that you can drop into your project if need be. PapaParse has no dependencies.
I have used it myself and can verify it works, is convenient, and is well-documented.
» npm install convert-csv-to-json
javascript - How to convert JSON to CSV format and store in a variable - Stack Overflow
How can i convert CSV file in json file in Javascript?
How to convert JSON to CSV
Convert csv to json
How to convert CSV to JSON online?
Can I convert CSV to a JSON array?
How to use the
Convert CSV to JSON Array Online for free?
Hello guys, I'm a data science student and i'm trying to convert csv file in json file for a project. First I convrted xlsx file in csv: this is the dataset structure:
My goal is to created a json dictionary from previously dataset with this structure:
{
"templ_1jpg.jpg121349": {
"filename": "templ_1jpg.jpg",
"size": 121349,
"regions": [
{
"shape_attributes": {
"name": "polygon",
"all_points_x": [
154,
157,
230,
275,
278,
218,
160,
112,
113,
154
],
"all_points_y": [
461,
461,
455,
495,
576,
625,
625,
563,
505,
463
]
},
"region_attributes": {
"name": "A"
}
},
[..]How can I convert it using Javascript? Thanks all.
» npm install csvtojson
A more elegant way to convert json to csv is to use the map function without any framework:
var json = json3.items
var fields = Object.keys(json[0])
var replacer = function(key, value) { return value === null ? '' : value }
var csv = json.map(function(row){
return fields.map(function(fieldName){
return JSON.stringify(row[fieldName], replacer)
}).join(',')
})
csv.unshift(fields.join(',')) // add header column
csv = csv.join('\r\n');
console.log(csv)
Output:
title,description,link,timestamp,image,embed,language,user,user_image,user_link,user_id,geo,source,favicon,type,domain,id
"Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)","Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China’s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store’s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone","http://wik.io/info/US/309201303","1326439500","","","","","","","","","wikio","http://wikio.com/favicon.ico","blogs","wik.io","2388575404943858468"
"Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)","SHANGHAI – Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone","http://wik.io/info/US/309198933","1326439320","","","","","","","","","wikio","http://wikio.com/favicon.ico","blogs","wik.io","16209851193593872066"
Update ES6 (2016)
Use this less dense syntax and also JSON.stringify to add quotes to strings while keeping numbers unquoted:
const items = json3.items
const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
const header = Object.keys(items[0])
const csv = [
header.join(','), // header row first
...items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
].join('\r\n')
console.log(csv)
Ok I finally got this code working:
<html>
<head>
<title>Demo - Covnert JSON to CSV</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>
<script type="text/javascript">
// JSON to CSV Converter
function ConvertToCSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
// Example
$(document).ready(function () {
// Create Object
var items = [
{ name: "Item 1", color: "Green", size: "X-Large" },
{ name: "Item 2", color: "Green", size: "X-Large" },
{ name: "Item 3", color: "Green", size: "X-Large" }];
// Convert Object to JSON
var jsonObject = JSON.stringify(items);
// Display JSON
$('#json').text(jsonObject);
// Convert JSON to CSV & Display CSV
$('#csv').text(ConvertToCSV(jsonObject));
});
</script>
</head>
<body>
<h1>
JSON</h1>
<pre id="json"></pre>
<h1>
CSV</h1>
<pre id="csv"></pre>
</body>
</html>
Thanks alot for all the support to all the contributors.
Praney
» npm install json-2-csv