1use std::collections::HashMap;
2
3use simple_json_parser::{parse, JSONKey, RootJSONValue};
4
5fn main() -> Result<(), Box<dyn std::error::Error>> {
6 let path = std::env::args().nth(1).ok_or("Expected first argument")?;
7 let content = std::fs::read_to_string(path)?;
8
9 pub type Object = HashMap<String, Value>;
10
11 #[derive(Debug)]
12 #[allow(dead_code)]
13 pub enum Value {
14 Object(Object),
15 String(String),
16 Number(String),
17 Boolean(bool),
18 Null,
19 }
20
21 impl Value {
22 pub fn new_empty_object() -> Self {
23 Self::Object(HashMap::new())
24 }
25
26 pub fn set<'a>(&'a mut self, keys: &'a [JSONKey<'a>], value: RootJSONValue<'a>) {
27 if let Value::Object(ref mut obj) = self {
28 if let [last] = keys {
29 let name = match last {
30 JSONKey::Slice(s) => (*s).to_string(),
31 JSONKey::Index(i) => i.to_string(),
32 };
33 let value = match value {
34 RootJSONValue::String(s) => Value::String(s.to_string()),
35 RootJSONValue::Number(n) => Value::Number(n.to_string()),
36 RootJSONValue::Boolean(v) => Value::Boolean(v),
37 RootJSONValue::Null => Value::Null,
38 };
39 let existing = obj.insert(name, value);
40 debug_assert!(existing.is_none());
41 } else if let [first, others @ ..] = keys {
42 let name = match first {
43 JSONKey::Slice(s) => (*s).to_string(),
44 JSONKey::Index(i) => i.to_string(),
45 };
46 obj.entry(name)
47 .or_insert_with(Value::new_empty_object)
48 .set(others, value);
49 } else {
50 unreachable!("empty keys")
51 }
52 } else {
53 unreachable!()
54 }
55 }
56 }
57
58 let mut root = Value::new_empty_object();
59
60 parse(&content, |keys, value| root.set(keys, value))?;
61
62 eprintln!("Parsed: {root:#?}");
63 Ok(())
64}