Skip to content

Commit 61452e4

Browse files
authored
Merge pull request #1152 from ccutrer/fix-numeric-key
add support for numeric keys in map literal
2 parents 5e414d3 + 5259a8d commit 61452e4

2 files changed

Lines changed: 12 additions & 1 deletion

File tree

src/main/java/com/hubspot/jinjava/el/ext/AstDict.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import de.odysseus.el.tree.impl.ast.AstIdentifier;
88
import de.odysseus.el.tree.impl.ast.AstLiteral;
99
import de.odysseus.el.tree.impl.ast.AstNode;
10+
import de.odysseus.el.tree.impl.ast.AstNumber;
1011
import de.odysseus.el.tree.impl.ast.AstString;
1112
import java.util.LinkedHashMap;
1213
import java.util.Map;
@@ -45,9 +46,14 @@ public Object eval(Bindings bindings, ELContext context) {
4546
} else {
4647
key = ((AstIdentifier) entryKey).getName();
4748
}
49+
} else if (entryKey instanceof AstNumber) {
50+
// This is a hack to treat numeric keys as string keys in the dictionary.
51+
// In most cases this is adequate since the keys are typically treated as
52+
// strings.
53+
key = Objects.toString(entryKey.eval(bindings, context));
4854
} else {
4955
throw new TemplateStateException(
50-
"Dict key must be a string or identifier, was: " + entryKey
56+
"Dict key must be a string, or identifier, or a number, was: " + entryKey
5157
);
5258
}
5359

src/test/java/com/hubspot/jinjava/el/ExtendedSyntaxBuilderTest.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,11 @@ public void complexMapLiteral() {
213213
assertThat((Map<String, Object>) map.get("Boston")).contains(entry("city", "Boston"));
214214
}
215215

216+
@Test
217+
public void mapLiteralWithNumericKey() {
218+
assertThat((Map<String, Object>) val("{0:'test'}")).contains(entry("0", "test"));
219+
}
220+
216221
@Test
217222
public void itParsesDictWithVariableRefs() {
218223
List<?> theList = Lists.newArrayList(1L, 2L, 3L);

0 commit comments

Comments
 (0)