Creating A CSV To JSON Data Converter with jQuery Parse Plugin

Creating A CSV To JSON Data Converter with jQuery Parse Plugin
File Size: 25.7 KB
Views Total:
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

Parse is a simple and fast jQuery plugin that allows to parse and convert comma-separated values (CSV) into JSON Data.

Features:

  • Supports custom delimiting characters in CSV data.
  • Has the ability to interpret the first row of parsed data as a header column.
  • Has the options of converting fields that are strictly numeric to a number type.

How to use it:

1. Include jQuery javascript library and jQuery parse in the page

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="jquery.parse.js"></script>

2. Create the html for a textarea based CSV To JSON Data converter.

<textarea id="tb" placeholder="CSV input"></textarea>

<!-- custom delimiting characters option -->
<input type="text" id="delim" value="," maxlength="1">


<!-- header option -->
<label>
<input type="checkbox" id="header" checked>
Header row</label>

<!-- Dynamic typing option -->
<label>
<input type="checkbox" id="dyntype" checked>
Dynamic typing</label>

<!-- Button to trigger the converter -->
<button id="btn">Parse</button>

<!-- Output container -->
<code id="output"></code>

3. The javascript.

<script>
$(function()
{
$('#btn').click(function()
{
var results = $.parse($('#tb').val(), {
delimiter: $("#delim").val(),
header: $('#header').is(':checked'),
dynamicTyping: $('#dyntype').is(':checked')
});

$('#output').text(JSON.stringify(results, undefined, 2));
});
});
</script>

4. The Options.

results = $.parse(csvString, {
delimiter: ",", // The delimiting character. Usually just a comma or tab. Can be set to anything anything except " or \n.
header: true, // If true, interpret the first row of parsed data as a header column; fields are returned separately from the data, and data will be returned keyed to its field name. If false, the parser simply returns an array (list) of arrays (rows), including the first column.
dynamicTyping: true // If true, fields that are strictly numeric will be converted to a number type. If false, each parsed datum is returned as a string.
});

Change log:

2014-07-17

  • Fix for special case of quotes around delimiter in quoted field

2014-07-16

v0.5.6 (2013-10-31)

  • Typo fix

v0.5.5 (2013-10-25)

  • Minified latest bug fix

v0.5.4 (2013-10-22)

  • Fixed IE8 compatibility issue

This awesome jQuery plugin is developed by mholt. For more Advanced Usages, please check the demo page or visit the official website.