This library is a small wrapper around the Liquid templating engine that recursively processes structured JSON values for Liquid templates.
Liquid JSON templates help templatize JSON files used in configuration or RPC transmission.
```rust use serdejson::json; let templatejson = json!({"this":"{{myval}}"}); let templatedata = json!({"myval": 5}); let tmpl = liquidjson::LiquidJson::new(templatejson); let actual = tmpl.render(&templatedata).unwrap();
let expected = json!({"this": 5}); // {{myval}} is replaced with 5 assert_eq!(actual, expected); ```
The serde
feature (enabled by default) exposes LiquidJsonValue
. LiquidJsonValue
is a wrapper around LiquidJson
(and serde_json::Value
) that lets you embed LiquidJson
templates in your structs, e.g.
```rust use serde_json::json;
struct YourStruct { innerliquid: liquidjson::LiquidJsonValue, }
let jsondata = json!({"innerliquid":"{{myval}}"});
let template_data = json!({"myval": 5});
let yours: YourStruct = serdejson::fromvalue(jsondata).unwrap(); let actual = yours.innerliquid.render(&template_data).unwrap();
```
This library extends the default Liquid filters with the following:
json
: parses a JSON string into a Liquid object (recursing through arrays/objects as necessary).each
: apply a template over every element in an array.output
: mark a Liquid value as the output value of the template. Useful when you want to return an array or an object instead of a string.base64_encode
: encode a value to a base64 string.base64_decode
: decode a base64 value to a string. This will error if the result is not a string.Those filters can combine to produce complex JSON structures from simple input data. E.g.:
The input data:
json
{
"to": ["john@example.com", "jane@example.com"]
}
Applied to the liquid JSON template:
json
{
"recipients" : "{{ to | each: '{ \"email\": \"{{ el }}\" }' | json | output }}"
}
Produces the JSON:
json
{
"recipients": [
{
"email": "john@example.com"
},
{
"email": "jane@example.com"
}
]
}