1use serde_json::Value;
10
11pub type Document = serde_json::Map<String, Value>;
12
13pub fn raw_values(doc: &Document, key: &str) -> Vec<Value> {
15 match doc.get(key) {
16 None => vec![Value::String(String::new())],
17 Some(Value::Array(values)) => values.clone(),
18 Some(value) => vec![value.clone()],
19 }
20}
21
22pub fn str_values(doc: &Document, key: &str) -> Vec<String> {
24 raw_values(doc, key).iter().map(py_str).collect()
25}
26
27pub fn first_str(doc: &Document, key: &str) -> Option<String> {
29 let value = raw_values(doc, key).into_iter().next()?;
30 if !truthy(&value) {
31 return None;
32 }
33 Some(py_str(&value))
34}
35
36pub fn first_f64(doc: &Document, key: &str) -> Option<f64> {
38 match raw_values(doc, key).into_iter().next()? {
39 Value::Number(n) => n.as_f64(),
40 Value::String(s) => s.trim().parse().ok(),
41 _ => None,
42 }
43}
44
45pub fn truthy(value: &Value) -> bool {
47 match value {
48 Value::Null => false,
49 Value::Bool(b) => *b,
50 Value::Number(n) => n.as_f64().is_some_and(|f| f != 0.0),
51 Value::String(s) => !s.is_empty(),
52 Value::Array(a) => !a.is_empty(),
53 Value::Object(o) => !o.is_empty(),
54 }
55}
56
57pub fn py_str(value: &Value) -> String {
59 match value {
60 Value::Null => "None".into(),
61 Value::Bool(true) => "True".into(),
62 Value::Bool(false) => "False".into(),
63 Value::String(s) => s.clone(),
64 Value::Number(n) => {
65 if n.is_f64() {
66 let f = n.as_f64().unwrap_or_default();
67 if f.fract() == 0.0 && f.abs() < 1e16 {
68 format!("{f:.1}")
69 } else {
70 format!("{f}")
71 }
72 } else {
73 n.to_string()
74 }
75 }
76 other => other.to_string(),
77 }
78}
79
80#[cfg(test)]
81mod tests {
82 use super::*;
83 use serde_json::json;
84
85 #[test]
86 fn reads_like_addok() {
87 let doc: Document = serde_json::from_value(
88 json!({"city": ["Paris", "Paname"], "postcode": 75001, "x": 1.0, "n": null}),
89 )
90 .unwrap();
91 assert_eq!(first_str(&doc, "city").as_deref(), Some("Paris"));
92 assert_eq!(first_str(&doc, "postcode").as_deref(), Some("75001"));
93 assert_eq!(py_str(&doc["x"]), "1.0");
94 assert_eq!(first_str(&doc, "n"), None);
95 assert_eq!(first_str(&doc, "missing"), None);
96 }
97}