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 Overflow
🌐
npm
npmjs.com › package › convert-csv-to-json
convert-csv-to-json - npm
1 month ago - Convert CSV files to JSON with no dependencies. Supports Node.js (Sync & Async), and Browser environments with full RFC 4180 compliance. Memory-efficient streaming for processing large files without loading them entirely into memory.
      » npm install convert-csv-to-json
    
Published   Jul 25, 2026
Version   4.66.0
Discussions

javascript - How to convert JSON to CSV format and store in a variable - Stack Overflow
I have a link that opens up JSON data in the browser, but unfortunately I have no clue how to read it. Is there a way to convert this data using JavaScript in CSV format and save it in JavaScript f... More on stackoverflow.com
🌐 stackoverflow.com
How can i convert CSV file in json file in Javascript?
Your JSON is broken and inconsistent, so no library would have been able to fix it. The best solution is to correct whatever code is fucking up your CSV, but I wrote some code to fix the existing problems and parse it. // This will be our final result var map = {}; // Split all rows into an array var rows = csv.split(/\n/g); // Get the object keys from the header row var keys = rows.shift().split(","); // Loop thru each row and construct our map rows.forEach(raw_row=>{ // Result for this row var row = {}; var row_key; // Split the row up into columns var columns = raw_row.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/); columns.forEach((column, index)=>{ // Get the key for the current column var key = keys[index]; // If there is no title for this column, skip it. if(!key) return; // The "name" column is the key for the row // based on the example JSON if(key === 'Name'){ row_key = column; return; } // The "Coordinates" key is supposed to be JSON, // but the JSON is all kinds of fucked up and needs to be repaired if(key === "Coordinates"){ // Replace "" with " column = column.replace(/""/g, '"'); // Trim leading and trailing double quotes column = column.substring(1, column.length-1); // Since some of the keys of the embedded JSON are not quoted, and therefore not valid JSON // We need to fix this.... column = column.replace(/([a-zA-Z_]+):/g, `"$1":`); // Replace the missing curlies and attempt to parse it try{ column = JSON.parse(`{${column}}`); }catch(e){} } // Create the row object row[key] = column; }); // Create the final object map[row_key] = row; }); then your final object will be in the `map` variable. Here's a fiddle: https://jsfiddle.net/rL0pja4u/ More on reddit.com
🌐 r/learnjavascript
7
5
April 28, 2021
How to convert JSON to CSV
I did a tutorial recently on taking form data and turning it into table rows that could be edited and the exported as a CSV. https://youtu.be/MsHrntNF0Z0 More on reddit.com
🌐 r/learnjavascript
14
49
February 10, 2023
Convert csv to json
If you have used the 'csvtojson' package and it is returning unexpected results, it might be due to the special characters (emojis) in your CSV file. The 'csvtojson' package handles special characters quite well. Please make sure that the file encoding is set to 'utf-8' to handle special characters like emojis. Let's take your existing code and modify it a bit to convert CSV data to JSON. const csvFilePath = path.join(__dirname, 'path_to_csv.csv'); const csv = require('csvtojson'); csv({ noheader: false, headers: ['Header1', 'Header2', 'Header3', ...] // Replace these with your CSV headers }) .fromFile(csvFilePath) .then((jsonObj)=>{ console.log(jsonObj); }) .catch((err) => { console.error(err); }); More on reddit.com
🌐 r/node
6
5
June 13, 2023
People also ask

How to convert CSV to JSON online?
To convert CSV to JSON, paste your CSV data or upload a file, then review the table in the editor. The CSV to JSON converter updates the result as you edit, so you can convert CSV to JSON and copy or download the final JSON output.
🌐
tableconvert.com
tableconvert.com › home › csv to json converter online - free csv json tool
CSV to JSON Converter Online - Free CSV JSON Tool
Can I convert CSV to a JSON array?
Yes. Use the object array output format to convert each CSV row into a JSON object.
🌐
tableconvert.com
tableconvert.com › home › csv to json converter online - free csv json tool
CSV to JSON Converter Online - Free CSV JSON Tool
How to use the Convert CSV to JSON Array Online for free?
Upload your CSV file, paste data, or extract from web pages using our free online table converter. Convert CSV to JSON instantly with real-time preview and advanced editing. This CSV to JSON converter lets you copy or download your JSON output right away.
🌐
tableconvert.com
tableconvert.com › home › csv to json converter online - free csv json tool
CSV to JSON Converter Online - Free CSV JSON Tool
🌐
Reddit
reddit.com › r/learnjavascript › how can i convert csv file in json file in javascript?
r/learnjavascript on Reddit: How can i convert CSV file in json file in Javascript?
April 28, 2021 -

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.

Top answer
1 of 3
3
Your JSON is broken and inconsistent, so no library would have been able to fix it. The best solution is to correct whatever code is fucking up your CSV, but I wrote some code to fix the existing problems and parse it. // This will be our final result var map = {}; // Split all rows into an array var rows = csv.split(/\n/g); // Get the object keys from the header row var keys = rows.shift().split(","); // Loop thru each row and construct our map rows.forEach(raw_row=>{ // Result for this row var row = {}; var row_key; // Split the row up into columns var columns = raw_row.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/); columns.forEach((column, index)=>{ // Get the key for the current column var key = keys[index]; // If there is no title for this column, skip it. if(!key) return; // The "name" column is the key for the row // based on the example JSON if(key === 'Name'){ row_key = column; return; } // The "Coordinates" key is supposed to be JSON, // but the JSON is all kinds of fucked up and needs to be repaired if(key === "Coordinates"){ // Replace "" with " column = column.replace(/""/g, '"'); // Trim leading and trailing double quotes column = column.substring(1, column.length-1); // Since some of the keys of the embedded JSON are not quoted, and therefore not valid JSON // We need to fix this.... column = column.replace(/([a-zA-Z_]+):/g, `"$1":`); // Replace the missing curlies and attempt to parse it try{ column = JSON.parse(`{${column}}`); }catch(e){} } // Create the row object row[key] = column; }); // Create the final object map[row_key] = row; }); then your final object will be in the `map` variable. Here's a fiddle: https://jsfiddle.net/rL0pja4u/
2 of 3
1
Hey! I actually built a tool that does exactly this. Just paste your CSV data and it converts to JSON instantly - no coding needed. You can choose between array of objects (which you need) or other formats. Here's how: Copy your CSV data Paste into freetextconvert.com/csv-to-json Select "Array of Objects" format Click convert For your nested structure, you might need to do a bit of post-processing, but it'll give you the clean JSON array to work with. No signup required, works in browser. Hope this helps with your future project!
🌐
CSVJSON
csvjson.com
CSVJSON - CSVJSON
Online Conversion Tools for Developers. CSV, JSON, SQL and JavaScript. Sponsored by Flatfile.
🌐
GitHub
gist.github.com › markcheno › 6c018efbe61cc5bbad31012d762e8af4
CSV to JSON Conversion in JavaScript · GitHub
CSV to JSON Conversion in JavaScript. GitHub Gist: instantly share code, notes, and snippets.
Find elsewhere
🌐
Joshtronic
joshtronic.com › 2022 › 05 › 15 › how-to-convert-csv-to-json-in-javascript
How to convert CSV to JSON in JavaScript - Joshtronic
May 15, 2022 - const file = '/path/to/your/file.csv'; const csvData = fs.readFileSync(file, 'utf8'); const jsonData = Papa.parse(csvData, { header: true });
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-convert-csv-to-json-in-javascript
How to Convert CSV to JSON in JavaScript ? - GeeksforGeeks
July 23, 2025 - It involves splitting the CSV text into lines and then splitting each line into individual values using commas as separators. By iterating through each line, excluding the header, we create a JSON object, with the first line's values serving ...
🌐
Table Convert
tableconvert.com › home › csv to json converter online - free csv json tool
CSV to JSON Converter Online - Free CSV JSON Tool
July 28, 2025 - Use these checks before copying or downloading the result. ... Paste CSV text or upload a file, then generate JSON from the parsed table. The first row can be used as keys so each record becomes a structured JSON object.
🌐
Js2ts
js2ts.com › home › csv to json converter
Convert CSV to JSON Online | CSV to JSON Converter — js2ts.com
The CSV to JSON converter parses CSV files and outputs a JSON array of objects, where each row becomes an object with column headers as keys. Paste any CSV data and get JSON ready for use in your application.
🌐
Medium
medium.com › @raghav.ddps2 › csv-to-json-conversion-with-only-core-modules-7c535afc7e0
CSV To JSON conversion with only core modules | by Raghav Maheshwari | Medium
June 30, 2019 - This is pretty simple, just use the writeFile function, specify the path and the data using JSON.stringify() and log out a success message with appropriate error handling. Following is the code for the same.
🌐
Jam
jam.dev › utilities › csv-to-json
CSV to JSON Converter | Free, Open Source & Ad-free
Just paste your CSV file and get the JSON result. Built with 💜 by the developers at Jam, using the open-source PapaParse package. Whether you're working on web development projects, data analysis, or integrating with APIs, this converter makes it easy to convert CSV files into JSON data.
🌐
npm
npmjs.com › package › csvtojson
csvtojson - npm
csvtojson module is a comprehensive nodejs csv parser to convert csv to json or column arrays. It can be used as node.js library / command line tool / or in browser.
      » npm install csvtojson
    
Published   Oct 29, 2025
Version   2.0.14
Top answer
1 of 16
300

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)
2 of 16
71

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

🌐
Retool
retool.com › utilities › convert-json-to-csv
Convert JSON to CSV | Retool
JSON is a text format that is ... are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language. A Comma Separated Values (CSV) file is a plain ...
🌐
npm
npmjs.com › package › json-2-csv
json-2-csv - npm
May 26, 2026 - It is also capable of converting CSV of the same form back into the original array of JSON documents. The columns headings will be used as the JSON document keys. All lines must have the same exact number of CSV values. ... Upgrading to v5 from v4?
      » npm install json-2-csv
    
Published   May 26, 2026
Version   5.5.11
🌐
Konklone
konklone.io › json
JSON to CSV Converter
There was an error parsing this JSON. If you're sure this JSON is valid, please file an issue. Below are the first few rows ( total). Download the entire CSV, show all rows, or show the raw data.
🌐
Qodex
qodex.ai › home › all tools › file convertors › json to csv converter
JSON to CSV Converter Online, Free & Instant
Download or copy, grab the CSV file or copy the output to your clipboard. JSON (JavaScript Object Notation) is a structured format commonly used in APIs and databases.
Rating: 4.9 ​ - ​ 60 votes
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-convert-json-object-to-csv-in-javascript
How to Convert JSON Object to CSV in JavaScript ? - GeeksforGeeks
July 23, 2025 - In this approach we are using nodejs to convert the object into csv. We import the csvjson library, which provides functions for converting CSV data to JSON and vice versa.