Skip to content

Commit

Permalink
Merge pull request #1152 from ccutrer/fix-numeric-key
Browse files Browse the repository at this point in the history
add support for numeric keys in map literal
  • Loading branch information
boulter authored Mar 22, 2024
2 parents 5e414d3 + 5259a8d commit 61452e4
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/main/java/com/hubspot/jinjava/el/ext/AstDict.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import de.odysseus.el.tree.impl.ast.AstIdentifier;
import de.odysseus.el.tree.impl.ast.AstLiteral;
import de.odysseus.el.tree.impl.ast.AstNode;
import de.odysseus.el.tree.impl.ast.AstNumber;
import de.odysseus.el.tree.impl.ast.AstString;
import java.util.LinkedHashMap;
import java.util.Map;
Expand Down Expand Up @@ -45,9 +46,14 @@ public Object eval(Bindings bindings, ELContext context) {
} else {
key = ((AstIdentifier) entryKey).getName();
}
} else if (entryKey instanceof AstNumber) {
// This is a hack to treat numeric keys as string keys in the dictionary.
// In most cases this is adequate since the keys are typically treated as
// strings.
key = Objects.toString(entryKey.eval(bindings, context));
} else {
throw new TemplateStateException(
"Dict key must be a string or identifier, was: " + entryKey
"Dict key must be a string, or identifier, or a number, was: " + entryKey
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,11 @@ public void complexMapLiteral() {
assertThat((Map<String, Object>) map.get("Boston")).contains(entry("city", "Boston"));
}

@Test
public void mapLiteralWithNumericKey() {
assertThat((Map<String, Object>) val("{0:'test'}")).contains(entry("0", "test"));
}

@Test
public void itParsesDictWithVariableRefs() {
List<?> theList = Lists.newArrayList(1L, 2L, 3L);
Expand Down

0 comments on commit 61452e4

Please sign in to comment.