From b2943b8fd0ab71e377987bd54e13894653aea3ee Mon Sep 17 00:00:00 2001 From: marilynel Date: Sun, 16 Mar 2025 12:50:58 -0700 Subject: [PATCH] fixed issue #943 Csv parsing skip last row if last line is missing newline --- src/main/java/org/json/CDL.java | 21 +++++++++++++++--- src/test/java/org/json/junit/CDLTest.java | 27 +++++++++++++++++++++++ 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/json/CDL.java b/src/main/java/org/json/CDL.java index b495de1..dd631bf 100644 --- a/src/main/java/org/json/CDL.java +++ b/src/main/java/org/json/CDL.java @@ -100,11 +100,15 @@ public class CDL { for (;;) { String value = getValue(x,delimiter); char c = x.next(); - if (value == null || - (ja.length() == 0 && value.length() == 0 && c != delimiter)) { + if (value != null) { + ja.put(value); + } else if (ja.length() == 0 && c != delimiter) { return null; + } else { + // This line accounts for CSV ending with no newline + ja.put(""); } - ja.put(value); + for (;;) { if (c == delimiter) { break; @@ -307,6 +311,17 @@ public class CDL { if (ja.length() == 0) { return null; } + + // The following block accounts for empty datasets (no keys or vals) + if (ja.length() == 1) { + JSONObject j = ja.getJSONObject(0); + if (j.length() == 1) { + String key = j.keys().next(); + if ("".equals(key) && "".equals(j.get(key))) { + return null; + } + } + } return ja; } diff --git a/src/test/java/org/json/junit/CDLTest.java b/src/test/java/org/json/junit/CDLTest.java index 0e3668b..e5eb9ed 100644 --- a/src/test/java/org/json/junit/CDLTest.java +++ b/src/test/java/org/json/junit/CDLTest.java @@ -168,6 +168,33 @@ public class CDLTest { } } + /** + * Csv parsing skip last row if last field of this row is empty #943 + */ + @Test + public void csvParsingCatchesLastRow(){ + String data = "Field 1,Field 2,Field 3\n" + + "value11,value12,\n" + + "value21,value22,"; + + JSONArray jsonArray = CDL.toJSONArray(data); + + JSONArray expectedJsonArray = new JSONArray(); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("Field 1", "value11"); + jsonObject.put("Field 2", "value12"); + jsonObject.put("Field 3", ""); + expectedJsonArray.put(jsonObject); + + jsonObject = new JSONObject(); + jsonObject.put("Field 1", "value21"); + jsonObject.put("Field 2", "value22"); + jsonObject.put("Field 3", ""); + expectedJsonArray.put(jsonObject); + + Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); + } + /** * Assert that there is no error for a single escaped quote within a properly embedded quote. */