diff --git a/src/app.js b/src/app.js index f6786c8..47da4be 100644 --- a/src/app.js +++ b/src/app.js @@ -204,6 +204,7 @@ function toCSV(data, opts){ if(headers){ if(opts.wrap){ headers = headers.map(function(item){ + item = item.replace(/"/g, '""'); return opts.wrap + item + opts.wrap; }); } @@ -226,7 +227,9 @@ function toCSV(data, opts){ if(csvJSON[keys[j]][i]){ csvJSON[keys[j]][i] = csvJSON[keys[j]][i].replace(replaceNewLinePattern, '\t'); if(opts.wrap){ - csvJSON[keys[j]][i] = opts.wrap + csvJSON[keys[j]][i] + opts.wrap; + var str = csvJSON[keys[j]][i]; + str = str.replace(/"/g, '""'); + csvJSON[keys[j]][i] = opts.wrap + str + opts.wrap; } row[row.length] = csvJSON[keys[j]][i]; }else{ diff --git a/tests/main.test.js b/tests/main.test.js index 272cc84..c5b3b5a 100644 --- a/tests/main.test.js +++ b/tests/main.test.js @@ -114,7 +114,35 @@ describe('toCSV', function() { expect(result).to.be.an('string'); done(); }); - + + it('should double quote a quote when wrap options set', function(done) { + var jsonWithQuote = { + "person": [ + { + "firstName": "Jane", + "lastName": "Doe", + "greeting": "Hello World" + }, + { + "firstName": "Agatha", + "lastName": "Doe", + "greeting": "This is a quote \"" + } + ] + }; + var opts = { + wrap: true + } + var result = csvjson.toCSV(jsonWithQuote, opts); + expect(result).to.be.an('string'); + expect(result).equals( + "\".person[].firstName\",\".person[].lastName\",\".person[].greeting\"\n" + + "\"Jane\",\"Doe\",\"Hello World\"\n" + + "\"Agatha\",\"Doe\",\"This is a quote \"\"\"" // should double quote a quote in CSV string. + ); + done(); + }); + });