Expand description
Serde helpers for values that need a JSON representation which JavaScript can decode without losing precision.
This crate exposes a single wrapper type, Jsone<T> which wraps any field or type,
and handles the lossless serialization and deserialization of values in Rust. You must
pair this with the frontend encoder or decoder to turn the response back to regular JavaScript.
Be aware if the decoder detects a bigint value, it will may return a JS BigInt object instead of a number
so your code must be able to handle this!
§Supported values
We support losslessly serializing and deserializing:
- special-case floating-point numbers like
f64::NAN,f64::INFINITY,f64::NEG_INFINITY - Rust integer types which are larger than
Number.MAX_SAFE_INTEGERor smaller thanNumber.MIN_SAFE_INTEGER
We do this by encoding them into a special JSON struct like:
- For special-cases we use the form
{ "$$jsone$remap$$": 1 }where each number represents a known special case. - For integer outside safe range:
{ "$$jsone$remap$$": "12345678901234567890" }
The JS decoder can find this object key and replace the whole object with the correct value, making end to end lossless serialization and deserialization possible.
§Example
use jsone::Jsone;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, PartialEq, Serialize)]
struct Payload {
id: Jsone<i32>,
}
let json = serde_json::to_string(&Payload { id: Jsone(42) }).unwrap();
assert_eq!(json, r#"{"id":42}"#);
let payload: Payload = serde_json::from_str(&json).unwrap();
assert_eq!(payload.id, Jsone(42));Structs§
- Jsone
- Serde wrapper that applies the remap logic.
Constants§
- JS_
RUNTIME - The JavaScript runtime for encoding and decoding.