expression
Validate and serialize structured JavaScript values
The Serde adapter converts between Rust data and JavaScript values, not necessarily JSON text. Decode the input into an explicit schema and validate application constraints separately. The sample accepts a count no greater than 100 and returns a record. Deserialization is not authorization. Expected result (NOT RUN): normalize_reading({count:5}) returns an object with count 5; count 101 and missing count throw. Common mistake: Assuming all JsValue values satisfy the expected schema or accepting a valid integer without checking its allowed range. Static Rust source module for the accompanying Cargo lab; not a standalone executable or ByteMind exercise.
Formal Syntax & Structure
rust syntaxrust
serde_wasm_bindgen::from_value; serde_wasm_bindgen::to_valueWorking Example
Example Snippetrust
use serde::{Deserialize, Serialize};use wasm_bindgen::prelude::*;#[derive(Deserialize, Serialize)]struct Reading { count: u32 }#[wasm_bindgen]pub fn normalize_reading(input: JsValue) -> Result<JsValue, JsValue> { let reading: Reading = serde_wasm_bindgen::from_value(input) .map_err(|_| JsValue::from_str("invalid reading"))?; if reading.count > 100 { return Err(JsValue::from_str("count too high")); } serde_wasm_bindgen::to_value(&reading).map_err(|_| JsValue::from_str("encoding failed"))}