Skip to content

rquickjs/rquickjs-serde

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

rquickjs serde

github crates

This is a serde serializer/deserializer for rquickjs Value.

Usage

use std::error::Error;

use serde::Serialize;
use rquickjs::{Runtime, Context};

#[derive(Serialize)]
struct User {
    fingerprint: String,
    location: String,
}

fn main() {
    let rt = Runtime::new().unwrap();
    let ctx = Context::full(&rt).unwrap();

    // Serialize to a Value<'_>
    let u = User {
        fingerprint: "0xF9BA143B95FF6D82".to_owned(),
        location: "Menlo Park, CA".to_owned(),
    };
    ctx.with(|ctx| {
        let v = rquickjs_serde::to_value(ctx, u).unwrap();
        let obj = v.into_object().unwrap();

        let fingerprint: String = obj.get("fingerprint").unwrap();
        assert_eq!(fingerprint, "0xF9BA143B95FF6D82");

        let location: String = obj.get("location").unwrap();
        assert_eq!(location, "Menlo Park, CA");
    });

    // Deserialize from a Value<'_>
    let v = ctx.with(|ctx| {
        ctx.eval::<Value<'_>, _>("var a = {fingerprint: '0xF9BA143B95FF6D82', location: 'Menlo Park, CA'};").unwrap();
        let val = ctx.globals().get("a").unwrap();
        let u: User = rquickjs_serde::from_value(val).unwrap();
        u
    });
    assert_eq!(v.fingerprint, "0xF9BA143B95FF6D82");
    assert_eq!(v.location, "Menlo Park, CA");
}

Strict mode

The implementation tries to make smart guesses when it can, for example the deserializer will fallback to converting BigInt to String. This is likely not what you want if you implement a serialization that is JSON compliant.

This is s why we offer the strict mode, that will stick to what the behaviour that the Javascript specification defines for JSON. Just switch the method to use it.

let u: User = rquickjs_serde::from_value_strict(val).unwrap();

Acknowledgements

This project includes code derived from the Javy project. See NOTICE for more details.

About

Serde serialization for RQuickJS

Topics

Resources

License

Stars

Watchers

Forks

Contributors 2

  •  
  •  

Languages