Diggsey / ijson

More efficient alternative to `serde_json::Value` which saves memory by interning primitive values and using tagged pointers.
Apache License 2.0
127 stars 14 forks source link

Using ijson in place of serde_json::Value #6

Closed rimutaka closed 2 years ago

rimutaka commented 3 years ago

What can be done to substitute serde_json::Value with ijson with 3rd party crates?

E.g. I am using Tera that takes serde_json::Value as input and puts it into an HTML template.

Diggsey commented 3 years ago

ijson::Value implements Serialize and Deserialize and so is usable in most places where serde_json::Value could be used. However, if a crate specifically requires serde_json::Value then there's not much that can be done (short of forking the crate).

rimutaka commented 3 years ago

Diggory, thanks for your quick reply. I wonder if you have an example for adapting code from Value to serde::ser::Serialize to make it compatible with ijson?

use serde_json::value::{to_value, Map, Value};

    /// Takes a serde-json `Value` and convert it into a `Context` with no overhead/cloning.
    pub fn from_value(obj: Value) -> TeraResult<Self> {
        match obj {
            Value::Object(m) => {
                let mut data = BTreeMap::new();
                for (key, value) in m {
                    data.insert(key, value);
                }
                Ok(Context { data })
            }
            _ => Err(Error::msg(
                "Creating a Context from a Value/Serialize requires it being a JSON object",
            )),
        }
    }

Full source: https://github.com/Keats/tera/blob/master/src/context.rs#L93

Sorry, I am not very familiar with serde::ser::Serialize. Feel free to ignore if it's not trivial. I might dig into it later on myself.

Diggsey commented 3 years ago

It should be very straightforward, eg. you can change match obj to match obj.destructure()

https://docs.rs/ijson/latest/ijson/struct.IValue.html#method.destructure

Or in this case, since you're only handling the object case, you can just use:

https://docs.rs/ijson/latest/ijson/struct.IValue.html#method.into_object