Function nereon::expand_vars[][src]

pub fn expand_vars(root: &mut Value) -> Result<(), String>

Perform variable interpolation within serde_json Value.

Recursively searches all strings within root for variables that can be expanded and expands these varialbles in place.

There are three types of expansion:

  • ${node:some.node} - substitutes some.node from root. some.node is the absolute path of the node within root.
  • ${file:some/file} - substitutes the expanded contents ofsome/file`
  • ${ENV:env_var} - substitutes the environment variable env_var

$$ expands to $

Note: node and file type substitutions can cause expand_vars to return an Err if the corresponding node or file isn't found. env substitutions will always succeed and use the empty string "" in place of the environment variable if it isn't set.

Examples

use std::env;

// substitute entire string with another
let mut value = json!({"user" : "${env:nereon_user}"});
env::set_var("nereon_user", "root");
expand_vars(&mut value);
assert_eq!(value, json!({"user" : "root"}));

// substitute a string for part of a string
let mut value = json!({"user" : "User is ${env:nereon_user}"});
expand_vars(&mut value);
assert_eq!(value, json!({"user" : "User is root"}));

// substitute a node for an entire string
let mut value = json!({
    "allowed" : ["root", "admin"],
    "users" : "${node:allowed}"
});
expand_vars(&mut value);
assert_eq!(value, json!({
    "allowed" : ["root", "admin"],
    "users" : ["root", "admin"]
}));

// this one fails ...
let mut value = json!({
    "user" : "${node:missing}",
    "file" : "${file:no-such-file}",
});
assert!(expand_vars(&mut value).is_err());

// ... but this succeeds
let mut value = json!({"env" : "${env:no_such_env_var}"});
expand_vars(&mut value);
assert_eq!(value, json!({"env" : ""}));

// $$ expansion
let mut value = json!({"node" : "$${node:example}"});
expand_vars(&mut value);
assert_eq!(value, json!({"node" : "${node:example}"}));