Skip to main content

runestick_json/
lib.rs

1//! The json package, providing access to functions to serialize and deserialize
2//! json.
3//!
4//! ## Usage
5//!
6//! Add the following to your `Cargo.toml`:
7//!
8//! ```toml
9//! runestick = "0.2"
10//! runestick-json = "0.2"
11//! ```
12//!
13//! Install it into your context:
14//!
15//! ```rust
16//! # fn main() -> runestick::Result<()> {
17//! let mut context = runestick::Context::with_default_packages()?;
18//! context.install(&runestick_json::module()?)?;
19//! # Ok(())
20//! # }
21//! ```
22//!
23//! Use it in Rune:
24//!
25//! ```rust,ignore
26//! use json;
27//!
28//! fn main() {
29//!     let data = json::from_string("{\"key\": 42}");
30//!     dbg(data);
31//! }
32//! ```
33
34use runestick::{Bytes, ContextError, Module, Value};
35
36fn from_bytes(bytes: &[u8]) -> runestick::Result<Value> {
37    Ok(serde_json::from_slice(&bytes)?)
38}
39
40/// Get value from json string.
41fn from_string(string: &str) -> runestick::Result<Value> {
42    Ok(serde_json::from_str(string)?)
43}
44
45/// Convert any value to a json string.
46fn to_string(value: Value) -> runestick::Result<String> {
47    Ok(serde_json::to_string(&value)?)
48}
49
50/// Convert any value to a json string.
51fn to_bytes(value: Value) -> runestick::Result<Bytes> {
52    let bytes = serde_json::to_vec(&value)?;
53    Ok(Bytes::from_vec(bytes))
54}
55
56/// Get the module for the bytes package.
57pub fn module() -> Result<Module, ContextError> {
58    let mut module = Module::new(&["json"]);
59    module.function(&["from_bytes"], from_bytes)?;
60    module.function(&["from_string"], from_string)?;
61    module.function(&["to_string"], to_string)?;
62    module.function(&["to_bytes"], to_bytes)?;
63    Ok(module)
64}