spreadsheet_to_json/
helpers.rs1use calamine::Data;
2use indexmap::IndexMap;
3use serde_json::{Number, Value};
4
5
6pub fn json_object_to_indexmap(json: Value) -> Option<IndexMap<String, Value>> {
7 json.as_object().map(|obj| {
8 obj.iter()
9 .map(|(k, v)| (k.to_string(), v.clone()))
10 .collect::<IndexMap<String, Value>>()
11 })
12}
13
14pub fn json_object_to_calamine_data(json: Value) -> Vec<Data> {
15 let mut cells = vec![];
16 if let Some(obj) = json.as_object() {
17 for (_k, v) in obj.to_owned() {
18 let cell = match v {
19 Value::Number(fl) => Data::Float(fl.as_f64().unwrap_or(0.0)),
20 Value::Bool(b) => Data::Bool(b),
21 Value::String(s) => Data::String(s),
22 Value::Null => Data::Empty,
23 _ => Data::Empty,
24 };
25 cells.push(cell);
26 }
27 }
28 cells
29}
30
31pub fn json_array_to_indexmaps(json: Value) -> Vec<IndexMap<String, Value>> {
32 json.as_array().unwrap().iter()
33 .map(|v| v.to_owned()).filter_map(json_object_to_indexmap)
34 .collect()
35}
36
37pub fn json_array_to_calamine_rows(json: Value) -> Vec<Vec<Data>> {
38 json.as_array().unwrap().iter()
39 .map(|v| v.to_owned()).map(json_object_to_calamine_data)
40 .collect()
41}
42
43pub fn float_value(value: f64) -> Value {
44 Value::Number(Number::from_f64(value).unwrap_or(Number::from_f64(0.0).unwrap()))
45}
46
47pub fn integer_value(value: i64) -> Value {
48 Value::Number(Number::from_i128(value as i128).unwrap_or(Number::from_i128(0).unwrap()))
49}
50
51pub fn string_value(value: &str) -> Value {
52 Value::String(String::from(value))
53}
54
55pub fn bool_value(value: bool) -> Value {
56 Value::Bool(value)
57}