Function tauri::api::ipc::serialize_js_with
source · pub fn serialize_js_with<T: Serialize, F: FnOnce(&str) -> String>(
value: &T,
options: SerializeOptions,
cb: F
) -> Result<String>
Expand description
Transforms & escapes a JSON value.
If it’s an object or array, JSON.parse(‘{json}’) is used, with the ‘{json}’ string properly escaped.
The return value of this function can be safely used on eval
calls.
Single quotes chosen because double quotes are already used in JSON. With single quotes, we only need to escape strings that include backslashes or single quotes. If we used double quotes, then there would be no cases that a string doesn’t need escaping.
The function takes a closure to handle the escaped string in order to avoid unnecessary allocations.
Safety
The ability to safely escape JSON into a JSON.parse(‘{json}’) relies entirely on 2 things.
serde_json
’s ability to correctly escape and format json into a string.- JavaScript engines not accepting anything except another unescaped, literal single quote character to end a string that was opened with it.
Examples
use tauri::api::ipc::{serialize_js_with, SerializeOptions};
#[derive(serde::Serialize)]
struct Foo {
bar: String,
}
let foo = Foo { bar: "x".repeat(20_000).into() };
let value = serialize_js_with(&foo, SerializeOptions::default(), |v| format!("console.log({})", v)).unwrap();
assert_eq!(value, format!("console.log(JSON.parse('{{\"bar\":\"{}\"}}'))", foo.bar));