json_serializer/lib.rs
1use std::collections::HashMap;
2use std::fmt::{Debug, Display};
3use std::fs::File;
4use std::io::prelude::*;
5use std::process;
6use std::str::FromStr;
7
8pub struct Json<V: FromStr + Debug + Display> {
9 data: HashMap<String, V>,
10}
11
12impl<V: FromStr + Debug + Display> Json<V> {
13 pub fn new() -> Self {
14 Self {
15 data: HashMap::new(),
16 }
17 }
18
19 /// Decodes a HashMap of JSON keys and values into a JSON string.
20 ///
21 /// # Examples
22 ///
23 /// ```rust
24 /// extern crate json_serializer;
25 /// use std::fs::File;
26 /// let json_data: Json<i32> = Json::new();
27 /// let f = File::open("source.json").unwrap();
28 /// json_data.decode(&mut f);
29 /// println!("Encoded Data:\n{}", json_data.encode(2));
30 /// ```
31 pub fn encode(&self, indent: usize) -> String {
32 let mut result = String::new();
33 result.push_str("{\n");
34 for key in self.data.keys() {
35 let value = self.data.get(key).unwrap();
36 let indent_space = " ".repeat(indent);
37 result.push_str(
38 format!("{}\"{}\":{}{},\n", indent_space, key, indent_space, value).as_str(),
39 );
40 }
41
42 result.push_str("}");
43 result
44 }
45
46 /// Encodes a JSON string read from an utf-8 encoded JSON file into a HashMap.
47 ///
48 /// # Examples
49 ///
50 /// ```rust
51 /// extern crate json_serializer;
52 /// use std::fs::File;
53 /// let json_data: Json<i32> = Json::new();
54 /// let f = File::open("source.json").unwrap();
55 /// json_data.decode(&mut f);
56 /// println!("Encoded Data:\n{}", json_data.encode(2));
57 /// ```
58 pub fn decode(&mut self, src: &mut File)
59 where
60 <V as FromStr>::Err: Debug + Display,
61 {
62 let mut contents = String::new();
63 src.read_to_string(&mut contents)
64 .expect("Error reading source file");
65
66 if !contents.starts_with("{") && !contents.ends_with("}") {
67 process::exit(1);
68 }
69
70 let parsed_contents = contents.replace("{", "").replace("}", "").replace("\n", "");
71
72 let lines: Vec<&str> = parsed_contents.split(",").collect();
73
74 for line in lines.into_iter() {
75 let line: Vec<&str> = line.trim().split(":").collect();
76 let key = line.get(0).unwrap().replace("\"", "");
77 let value = line
78 .get(1)
79 .expect("Value might be empty")
80 .trim()
81 .replace("\"", "");
82
83 let parsed_value: V = match value.parse() {
84 Ok(v) => v,
85 Err(e) => panic!("{}", e),
86 };
87
88 self.data.insert(key, parsed_value);
89 }
90 }
91
92 /// Gets all the keys in the HashMap, and collects it into a Vec<String>
93 ///
94 /// # Examples
95 ///
96 /// ```
97 /// extern crate json_serializer;
98 /// use std::fs::File;
99 /// let json_data: Json<i32> = Json::new();
100 /// let f = File::open("source.json").unwrap();
101 /// json_data.decode(&mut f);
102 /// for json_data.get_keys().map(|key| {
103 /// println!(key);
104 /// });
105 /// ```
106 pub fn get_keys(&self) -> Vec<&String> {
107 self.data.keys().collect::<Vec<&String>>()
108 }
109
110 /// Gets all the keys in the HashMap, and collects it into a Vec<String>
111 ///
112 /// # Examples
113 ///
114 /// ```
115 /// extern crate json_serializer;
116 /// use std::fs::File;
117 /// let json_data: Json<i32> = Json::new();
118 /// let f = File::open("source.json").unwrap();
119 /// json_data.decode(&mut f);
120 /// for json_data.get_values().map(|val| {
121 /// println!("{:?}", val);
122 /// });
123 /// ```
124 pub fn get_values(&self) -> Vec<&V> {
125 self.data.values().collect::<Vec<&V>>()
126 }
127}
128
129#[cfg(test)]
130mod tests {
131 use super::*;
132
133 #[test]
134 fn test() {
135 let mut json_data: Json<i32> = Json::new();
136 let mut src = File::open("sample.json").unwrap();
137
138 json_data.decode(&mut src);
139
140 let encoded_data = json_data.encode(2);
141 let mut actual = String::new();
142 let mut f = File::open("sample.json").unwrap();
143 f.read_to_string(&mut actual).unwrap();
144
145 assert_eq!(actual, encoded_data);
146 }
147}