Skip to content

Commit d6efc4b

Browse files
committed
Escape nested quote with an additional quote
According to RFC 4180 the proper way to escape double-quotes in CSV data is to prepend an additional double-quote character: > If double-quotes are used to enclose fields, then a double-quote > appearing inside a field must be escaped by preceding it with > another double quote. Currently we escape double-quotes using a backslash. Opening such a file in Microsoft Excel and/or Apple Numbers breaks the column layout, i.e. the value containing the double quote is interpretted as multiple columns instead of one. On the contrary, escaping using an extra double-quote preserves the expected column layout in both Microsoft Excel and Apple Numbers. See also: - https://tools.ietf.org/html/rfc4180
1 parent f76048b commit d6efc4b

File tree

3 files changed

+3
-4
lines changed

3 files changed

+3
-4
lines changed

lib/csv-2-json.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -175,9 +175,8 @@ var splitLine = function (line) {
175175
stateVariables.parsingValue = true;
176176
stateVariables.startIndex = index + 1;
177177
}
178-
else if (character === "\\" && charAfter === options.DELIMITER.WRAP && stateVariables.insideWrapDelimiter) {
178+
else if (character === options.DELIMITER.WRAP && charAfter === options.DELIMITER.WRAP && stateVariables.insideWrapDelimiter) {
179179
line = line.slice(0, index) + line.slice(index+1); // Remove the current character from the line
180-
index--; // Move to position before to prevent moving ahead and skipping a character
181180
lastCharacterIndex--; // Update the value since we removed a character
182181
}
183182
// Otherwise increment to the next character

lib/json-2-csv.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ var convertField = function (value) {
133133
} else if (_.isBoolean(value)) { // If we have a boolean (avoids false being converted to '')
134134
return options.DELIMITER.WRAP + convertValue(value) + options.DELIMITER.WRAP;
135135
}
136-
value = options.DELIMITER.WRAP && value ? value.replace(new RegExp(options.DELIMITER.WRAP, 'g'), "\\"+options.DELIMITER.WRAP) : value;
136+
value = options.DELIMITER.WRAP && value ? value.replace(new RegExp(options.DELIMITER.WRAP, 'g'), options.DELIMITER.WRAP + options.DELIMITER.WRAP) : value;
137137
return options.DELIMITER.WRAP + convertValue(value) + options.DELIMITER.WRAP; // Otherwise push the current value
138138
};
139139

test/CSV/quoted/nestedQuotes.csv

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
"a string"
22
"with a description"
3-
"with a description and \"quotes\""
3+
"with a description and ""quotes"""

0 commit comments

Comments
 (0)