Skip to content

Commit 49df9f8

Browse files
committed
Preserve JSON null when indexing into an array
1 parent 47a17cc commit 49df9f8

2 files changed

Lines changed: 22 additions & 3 deletions

File tree

src/main/java/com/dashjoin/jsonata/Jsonata.java

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -502,7 +502,10 @@ Frame createFrameFromTuple(Frame environment, Map<String, Object> tuple) {
502502
if( input instanceof JList && ((JList)input).tupleStream) {
503503
((JList)results).tupleStream = true;
504504
}
505-
if (!(input instanceof List)) { // isArray
505+
if (input == null) {
506+
// undefined input yields undefined output; skip filtering entirely
507+
input = Utils.createSequence();
508+
} else if (!(input instanceof List)) { // isArray
506509
input = Utils.createSequence(input);
507510
}
508511
if (predicate.type.equals("number")) {
@@ -511,8 +514,12 @@ Frame createFrameFromTuple(Frame environment, Map<String, Object> tuple) {
511514
// count in from end of array
512515
index = ((List)input).size() + index;
513516
}
514-
var item = 0<=index && index<((List)input).size() ? ((List)input).get(index) : null;
515-
if(item != null) {
517+
if (0<=index && index<((List)input).size()) {
518+
var item = ((List)input).get(index);
519+
// Preserve JSON null at this index (vs. out-of-bounds, which is undefined)
520+
if (item == null) {
521+
item = NULL_VALUE;
522+
}
516523
if(item instanceof List) {
517524
results = (List)item;
518525
} else {

src/test/java/com/dashjoin/jsonata/NullSafetyTest.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,18 @@ public void testSingleNull() {
7171
Assertions.assertEquals(1, x);
7272
}
7373

74+
@Test
75+
public void testArrayIndexPreservesNull() {
76+
// Indexing into an array element that is JSON null must yield null,
77+
// not be filtered out as if it were undefined.
78+
Map<String, Object> data = Map.of("data", List.of(
79+
Arrays.asList(1, null, 3),
80+
Arrays.asList(2, null, 4),
81+
Arrays.asList(3, null, 5)));
82+
Object res = jsonata("[$map(data, function($row) { $row[1] })]").evaluate(data);
83+
Assertions.assertEquals(Arrays.asList(null, null, null), res);
84+
}
85+
7486
@Test
7587
public void testFilterNullLookup() {
7688
var x = Jsonata.jsonata("$filter($, function($v, $i, $a){$lookup($v, 'content')})").evaluate(

0 commit comments

Comments
 (0)