Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for numeric keys in map literal #1152

Merged
merged 3 commits into from
Mar 22, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 = entryKey.eval(bindings, context).toString();
ccutrer marked this conversation as resolved.
Show resolved Hide resolved
} 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 @@ -187,6 +187,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