Browse Source

Merge pull request #70 from jscheid/per-column-quotes

Add support for per-column quoting in Papa.unparse
pull/72/merge
Matt Holt 11 years ago
parent
commit
85479820d9
  1. 12
      papaparse.js
  2. 4
      tests/test-cases.js

12
papaparse.js

@ -282,7 +282,8 @@
_delimiter = _config.delimiter; _delimiter = _config.delimiter;
} }
if (typeof _config.quotes === 'boolean') if (typeof _config.quotes === 'boolean'
|| _config.quotes instanceof Array)
_quotes = _config.quotes; _quotes = _config.quotes;
if (typeof _config.newline === 'string') if (typeof _config.newline === 'string')
@ -321,7 +322,7 @@
{ {
if (i > 0) if (i > 0)
csv += _delimiter; csv += _delimiter;
csv += safe(fields[i]); csv += safe(fields[i], i);
} }
if (data.length > 0) if (data.length > 0)
csv += _newline; csv += _newline;
@ -337,7 +338,7 @@
if (col > 0) if (col > 0)
csv += _delimiter; csv += _delimiter;
var colIdx = hasHeader && dataKeyedByField ? fields[col] : col; var colIdx = hasHeader && dataKeyedByField ? fields[col] : col;
csv += safe(data[row][colIdx]); csv += safe(data[row][colIdx], col);
} }
if (row < data.length - 1) if (row < data.length - 1)
@ -348,14 +349,15 @@
} }
// Encloses a value around quotes if needed (makes a value safe for CSV insertion) // Encloses a value around quotes if needed (makes a value safe for CSV insertion)
function safe(str) function safe(str, col)
{ {
if (typeof str === "undefined") if (typeof str === "undefined")
return ""; return "";
str = str.toString().replace(/"/g, '""'); str = str.toString().replace(/"/g, '""');
var needsQuotes = _quotes var needsQuotes = (typeof _quotes === 'boolean' && _quotes)
|| (_quotes instanceof Array && _quotes[col])
|| hasAny(str, global.Papa.BAD_DELIMITERS) || hasAny(str, global.Papa.BAD_DELIMITERS)
|| str.indexOf(_delimiter) > -1 || str.indexOf(_delimiter) > -1
|| str.charAt(0) == ' ' || str.charAt(0) == ' '

4
tests/test-cases.js

@ -542,13 +542,13 @@ var UNPARSE_TESTS = [
{ {
description: "Force quotes around certain fields only", description: "Force quotes around certain fields only",
input: [['a', 'b', 'c'], ['d', 'e', 'f']], input: [['a', 'b', 'c'], ['d', 'e', 'f']],
config: { quotes: [0, 2] }, config: { quotes: [true, false, true] },
expected: '"a",b,"c"\r\n"d",e,"f"' expected: '"a",b,"c"\r\n"d",e,"f"'
}, },
{ {
description: "Force quotes around certain fields only (with header row)", description: "Force quotes around certain fields only (with header row)",
input: [{ "Col1": "a", "Col2": "b", "Col3": "c" }, { "Col1": "d", "Col2": "e", "Col3": "f" }], input: [{ "Col1": "a", "Col2": "b", "Col3": "c" }, { "Col1": "d", "Col2": "e", "Col3": "f" }],
config: { quotes: [0, 2] }, config: { quotes: [true, false, true] },
expected: '"Col1",Col2,"Col3"\r\n"a",b,"c"\r\n"d",e,"f"' expected: '"Col1",Col2,"Col3"\r\n"a",b,"c"\r\n"d",e,"f"'
}, },
{ {

Loading…
Cancel
Save