Skip to content

Commit

Permalink
added 'json' filter
Browse files Browse the repository at this point in the history
  • Loading branch information
msangel committed Jun 1, 2024
1 parent 416d98a commit f241e62
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/main/java/liqp/filters/Filters.java
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ public final class Filters {
new Upcase(), //
new Url_Decode(), //
new Url_Encode(), //
new Where() //
new Where(), //
new Json() //
);

static Filters JEKYLL_EXTRA_FILTERS = Filters.of( //
Expand Down
23 changes: 23 additions & 0 deletions src/main/java/liqp/filters/Json.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package liqp.filters;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import liqp.TemplateContext;
import liqp.TemplateParser;

public class Json extends Filter {
@Override
public Object apply(Object value, TemplateContext context, Object... params) {
ObjectMapper mapper = context.getParser().mapper;

try {
return mapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
context.addError(e);
if (context.getErrorMode() == TemplateParser.ErrorMode.STRICT) {
throw new RuntimeException(e.getMessage(), e);
}
return value;
}
}
}
31 changes: 31 additions & 0 deletions src/test/java/liqp/filters/JsonTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package liqp.filters;

import liqp.Template;
import liqp.TemplateParser;
import org.junit.Test;

import java.util.HashMap;

import static org.junit.Assert.*;

public class JsonTest {

@Test
public void testWhenStringIsInputShouldBeStringified() {
Template template = TemplateParser.DEFAULT.parse("{{ 'Hello, World!' | json }}");
String rendered = template.render();
assertEquals("\"Hello, World!\"", rendered);
}

@Test
public void testWhenObjectIsInputShouldBeStringified() {
Template template = TemplateParser.DEFAULT.parse("{{ obj | json }}");
java.util.Map<String, Object> map = new HashMap<>();
java.util.Map<String, Object> nested = new HashMap<>();
nested.put("key", "value");
map.put("obj", nested);

String rendered = template.render(map);
assertEquals("{\"key\":\"value\"}", rendered);
}
}

0 comments on commit f241e62

Please sign in to comment.