Skip to content

Commit f6f3563

Browse files
chrisirhcccutrer
authored andcommitted
add support for numeric keys in dictionary
This is a hack to support numeric keys declared in map literals. Most of such usages typically use the keys as if they were strings, so this hack is likely safe. A hack is used as opposed to overhauling all maps used since full support would require overhauling all maps types to `Map<Object, Object>` which seems overkill.
1 parent 6003ef0 commit f6f3563

2 files changed

Lines changed: 11 additions & 0 deletions

File tree

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

Lines changed: 6 additions & 0 deletions
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,6 +46,11 @@ 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 = entryKey.eval(bindings, context).toString();
4854
} else {
4955
throw new TemplateStateException(
5056
"Dict key must be a string or identifier, was: " + entryKey

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

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

190+
@Test
191+
public void mapLiteralWithNumericKey() {
192+
assertThat((Map<String, Object>) val("{0:'test'}")).contains(entry("0", "test"));
193+
}
194+
190195
@Test
191196
public void itParsesDictWithVariableRefs() {
192197
List<?> theList = Lists.newArrayList(1L, 2L, 3L);

0 commit comments

Comments
 (0)