Skip to main content

typst_template/convert/
serde_json.rs

1use serde_json::{Map, Number, Value as Json};
2use typst::foundations::{Decimal, Dict, Value};
3
4use crate::{ToDict, ToValue};
5
6impl ToValue for Json {
7    fn into_value(self) -> Value {
8        match self {
9            Json::Null => Value::None,
10            Json::Bool(value) => Value::Bool(value),
11            Json::Number(number) => number_into_value(number),
12            Json::String(value) => Value::Str(value.into()),
13            Json::Array(values) => Value::Array(values.into_iter().map(ToValue::into_value).collect()),
14            Json::Object(map) => Value::Dict(map.into_dict()),
15        }
16    }
17}
18
19impl ToDict for Map<String, Json> {
20    fn into_dict(self) -> Dict {
21        let mut dict = Dict::new();
22        for (key, value) in self {
23            dict.insert(key.into(), value.into_value());
24        }
25        dict
26    }
27}
28
29impl ToValue for Map<String, Json> {
30    fn into_value(self) -> Value {
31        Value::Dict(self.into_dict())
32    }
33}
34
35fn number_into_value(number: Number) -> Value {
36    if let Some(int) = number.as_i64() {
37        Value::Int(int)
38    } else if let Some(uint) = number.as_u64() {
39        i64::try_from(uint)
40            .map(Value::Int)
41            .unwrap_or(Value::Float(uint as f64))
42    } else if let Some(float) = number.as_f64() {
43        Value::Float(float)
44    } else {
45        // Arbitrary-precision number: keep full precision as a decimal, falling
46        // back to a string if it doesn't fit.
47        match number.to_string().parse::<Decimal>() {
48            Ok(decimal) => Value::Decimal(decimal),
49            Err(_) => Value::Str(number.to_string().into()),
50        }
51    }
52}