csvjson-csv2json
Version:
Converts CSV to JSON. Powers the most used online tool CSVJSON https://www.csvjson.com/csv2json. Used by thousands everyday.
113 lines (107 loc) • 2.7 kB
HTML
<!doctype html>
<html lang="en">
<head>
<title>CSVJSON's csv2json Test</title>
</head>
<body>
<h1>CSVJSON's csv2json Test</h1>
<h2>Test</h2>
<pre>
const csv = `album, year, US_peak_chart_post
The White Stripes, 1999, -
De Stijl, 2000, -
White Blood Cells, 2001, 61
Elephant, 2003, 6
Get Behind Me Satan, 2005, 3
Icky Thump, 2007, 2
Under Great White Northern Lights, 2010, 11
Live in Mississippi, 2011, -
Live at the Gold Dollar, 2012, -
Nine Miles from the White City, 2013, -`;
const json = CSVJSON.csv2json(csv, {parseNumbers: true});
</pre>
<h2>Expected</h2>
<pre id="expected">[
{
"album": "The White Stripes",
"year": 1999,
"US_peak_chart_post": "-"
},
{
"album": "De Stijl",
"year": 2000,
"US_peak_chart_post": "-"
},
{
"album": "White Blood Cells",
"year": 2001,
"US_peak_chart_post": 61
},
{
"album": "Elephant",
"year": 2003,
"US_peak_chart_post": 6
},
{
"album": "Get Behind Me Satan",
"year": 2005,
"US_peak_chart_post": 3
},
{
"album": "Icky Thump",
"year": 2007,
"US_peak_chart_post": 2
},
{
"album": "Under Great White Northern Lights",
"year": 2010,
"US_peak_chart_post": 11
},
{
"album": "Live in Mississippi",
"year": 2011,
"US_peak_chart_post": "-"
},
{
"album": "Live at the Gold Dollar",
"year": 2012,
"US_peak_chart_post": "-"
},
{
"album": "Nine Miles from the White City",
"year": 2013,
"US_peak_chart_post": "-"
}
]</pre>
<h2>Execution</h2>
<pre id="execution"></pre>
<h2>Test Result</h2>
<p id="result"></p>
<script type="text/javascript" src="csv2json.js"></script>
<script>
(function() {
const csv = `album, year, US_peak_chart_post
The White Stripes, 1999, -
De Stijl, 2000, -
White Blood Cells, 2001, 61
Elephant, 2003, 6
Get Behind Me Satan, 2005, 3
Icky Thump, 2007, 2
Under Great White Northern Lights, 2010, 11
Live in Mississippi, 2011, -
Live at the Gold Dollar, 2012, -
Nine Miles from the White City, 2013, -`;
const json = CSVJSON.csv2json(csv, {parseNumbers: true});
const expected = JSON.parse(document.getElementById('expected').innerText);
const execution = document.getElementById('execution');
const result = document.getElementById('result');
execution.innerText = JSON.stringify(json, null, 2);
if (JSON.stringify(json) == JSON.stringify(expected)) {
result.innerText = 'Success!';
} else {
result.innerText = 'Failed.';
}
}.call(this));
</script>
</body>
</html>