json-template
json-template
is a library that allows you to create JSON templates.
[file.json]
[additional.json]
Can be rendered to
Functionalities
Chained resolver
Every path segment is a placeholder
Functions
Built-in functions
Function | Description |
---|---|
{file:path} |
Loads a file from a relative path. Its base directory is automatically set if you deserialize a file. You can also set it manually using Context::set_directory . |
{string:path} |
Transforms a serde_json::Value to serde_json::Value::String . It's useful if you need to deserialize a Number as a String. |
{compose:{a}, {b}, ...} |
Composes N objects together. If the property doesn't exist, it will be added. If the property is an array, both arrays will be concatenated. Inputs are placeholders. |
Check Custom Functions
code example to learn how to create a custom function.
Code examples
You can always check the tests :)
From memory
use *;
use ;
let json = r#"{
"data": {
"name": "Danilo",
"age": 36
},
"name": "{data.name}",
"age": "{data.age}",
"age_str": "{string:data.age}",
"info": "{data.name} is {data.age} years old.",
"time": "{data.time}"
}"#;
let context = new
.with_data;
let data: Data = new.deserialize_with_context.unwrap;
assert_eq!
Note that the age_str
field is a string, while the age
field is a number.
Simple "{age}"
placeholders are replaced with the corresponding value in the JSON object.
"{string:age}"
placeholders are replaced with the corresponding value in the JSON object as a string.
Formatted placeholders like "{data.name} is {data.age} years old."
are replaced with the corresponding values in the JSON object as strings.
Even though "{string:data.name} is {string:data.age} years old."
would work, it is not necessary.
From file
use *;
use ;
use PathBuf;
let json = r#"{
"data": "{file:tests/data.json}",
"name": "{data.name}",
"age": "{data.age}",
"age_str": "{string:data.age}",
"info": "{data.name} is {data.age} years old.",
"time": "{data.time}"
}"#;
let directory = from;
let context = new
.with_data
.with_directory;
let data: Data = new.deserialize_with_context.unwrap;
assert_eq!
or simply
use *;
use ;
use PathBuf;
let file = from
.join
.join;
let context = new
.with_data;
let data: Data = new.deserialize_with_context.unwrap;
assert_eq!
Custom functions
use *;
use ;
let value = json!;
let context = new.with_function;
let data: Time = new.deserialize_with_context.expect;
assert_eq!;