Skip to content

Commit b2943b8

Browse files
committed
fixed issue #943 Csv parsing skip last row if last line is missing newline
1 parent 76ee431 commit b2943b8

File tree

2 files changed

+45
-3
lines changed

2 files changed

+45
-3
lines changed

src/main/java/org/json/CDL.java

+18-3
Original file line numberDiff line numberDiff line change
@@ -100,11 +100,15 @@ public static JSONArray rowToJSONArray(JSONTokener x, char delimiter) throws JSO
100100
for (;;) {
101101
String value = getValue(x,delimiter);
102102
char c = x.next();
103-
if (value == null ||
104-
(ja.length() == 0 && value.length() == 0 && c != delimiter)) {
103+
if (value != null) {
104+
ja.put(value);
105+
} else if (ja.length() == 0 && c != delimiter) {
105106
return null;
107+
} else {
108+
// This line accounts for CSV ending with no newline
109+
ja.put("");
106110
}
107-
ja.put(value);
111+
108112
for (;;) {
109113
if (c == delimiter) {
110114
break;
@@ -307,6 +311,17 @@ public static JSONArray toJSONArray(JSONArray names, JSONTokener x, char delimit
307311
if (ja.length() == 0) {
308312
return null;
309313
}
314+
315+
// The following block accounts for empty datasets (no keys or vals)
316+
if (ja.length() == 1) {
317+
JSONObject j = ja.getJSONObject(0);
318+
if (j.length() == 1) {
319+
String key = j.keys().next();
320+
if ("".equals(key) && "".equals(j.get(key))) {
321+
return null;
322+
}
323+
}
324+
}
310325
return ja;
311326
}
312327

src/test/java/org/json/junit/CDLTest.java

+27
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,33 @@ public void unbalancedEscapedQuote(){
168168
}
169169
}
170170

171+
/**
172+
* Csv parsing skip last row if last field of this row is empty #943
173+
*/
174+
@Test
175+
public void csvParsingCatchesLastRow(){
176+
String data = "Field 1,Field 2,Field 3\n" +
177+
"value11,value12,\n" +
178+
"value21,value22,";
179+
180+
JSONArray jsonArray = CDL.toJSONArray(data);
181+
182+
JSONArray expectedJsonArray = new JSONArray();
183+
JSONObject jsonObject = new JSONObject();
184+
jsonObject.put("Field 1", "value11");
185+
jsonObject.put("Field 2", "value12");
186+
jsonObject.put("Field 3", "");
187+
expectedJsonArray.put(jsonObject);
188+
189+
jsonObject = new JSONObject();
190+
jsonObject.put("Field 1", "value21");
191+
jsonObject.put("Field 2", "value22");
192+
jsonObject.put("Field 3", "");
193+
expectedJsonArray.put(jsonObject);
194+
195+
Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray);
196+
}
197+
171198
/**
172199
* Assert that there is no error for a single escaped quote within a properly embedded quote.
173200
*/

0 commit comments

Comments
 (0)