Expand description

Serialize serde::Serialize values to JavaScript using serde_json.

Serialization

The Serialized item can help you create a valid JavaScript value out of a serde_json::value::RawValue, along with some helpful options. It implements fmt::Display for direct use, but you can also manually remove it from the new-type with Serialized::into_string().

use serialize_to_javascript::{Options, Serialized};

fn main() -> serialize_to_javascript::Result<()> {
    let raw_value = serde_json::value::to_raw_value("foo'bar")?;
    let serialized = Serialized::new(&raw_value, &Options::default());
    assert_eq!(serialized.into_string(), "JSON.parse('\"foo\\'bar\"')");
    Ok(())
}

Templating

Because of the very common case of wanting to include your JavaScript values into existing JavaScript code, this crate also provides some templating features. Template helps you map struct fields into template values, while DefaultTemplate lets you attach it to a specific JavaScript file. See their documentation for more details on how to create and use them.

Templated names that are replaced inside templates are __TEMPLATE_my_field__ where my_field is a field on a struct implementing Template. Raw (#[raw] field annotation) value template names use __RAW_my_field__. Raw values are inserted directly without ANY serialization whatsoever, so being extra careful where it is used is highly recommended.

use serialize_to_javascript::{default_template, DefaultTemplate, Options, Serialized, Template};

#[derive(Template)]
#[default_template("../tests/keygen.js")]
struct Keygen<'a> {
    key: &'a str,
    length: usize,

    #[raw]
    optional_script: &'static str,
}

fn main() -> serialize_to_javascript::Result<()> {
    let keygen = Keygen {
        key: "asdf",
        length: 4,
        optional_script: "console.log('hello, from my optional script')",
    };

    let output: Serialized = keygen.render_default(&Options::default())?;

    Ok(())
}

Structs

This type represents all possible errors that can occur when serializing or deserializing JSON data.

Optional settings to pass to the templating system.

Reference to a range of bytes encompassing a single valid JSON value in the input data.

Serialized JavaScript output.

Traits

A Template with an attached default template.

A struct that contains serde::Serialize data to insert into a template.

Type Definitions

Alias for a Result with the error type serde_json::Error.

Attribute Macros

Automatically derive DefaultTemplate for a Template from the passed path.

Derive Macros

Automatically derive Template from a struct with valid input fields.