Hopefully this is enough context for the question...
Using Handlebars with Rust, I'm trying to implement a handler to handle this input:
{{toJSON JSON_OBJ_OR_NONE}}
where JSON_OBJ_OR_NONE is either a valid fragment of JSON like
{
"abc": 123,
"def": ["g", "h", "i"],
"jkl": {
"m": 1,
"n": "op"
}
}
or nothing (an empty string).
What it should return is either a pretty-printed version of the supplied JSON, or "{}" if JSON_OBJ_OR_NONE is empty.
The supplied JSON fragment is completely arbitrary; it could contain any valid JSON, or an empty string. Output should be pretty-printed.
I've tried to implement this in a bunch of different ways, and I'm currently at
handlebars_helper!(toJSON: |json_obj_or_none: str|
if json_obj_or_none.is_empty() {
"{}"
} else {
let s = serde_json::to_string_pretty(&json_obj_or_none).is_ok().to_string();
&s[..]
});
This looks close, but I'm seeing
error[E0597]: `s` does not live long enough
--> src/main.rs:145:10
|
145 | &s[..]
| -^----
| ||
| |borrowed value does not live long enough
| borrow later used here
146 | });
| - `s` dropped here while still borrowed
when I compile it
While this seems to be close to a working solution, I suspect there's a much more elegant way of coding it.