1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use serde_json;
use super::create_io_error;
use super::data_struct::{Row, Tabular};
use super::{is_debug, read_file, str_to_basictypes, write_file, BasicTypes};
use serde_json::Value;
use std::io::Error;
pub fn read_json(path: &str) -> Result<Tabular, Error> {
let text = read_file(path)?;
parse_json(&text)
}
pub fn parse_json(text: &str) -> Result<Tabular, Error> {
let value: Value = serde_json::from_str(text)?;
if is_debug() {
println!("{:?}", value);
}
let data = match value {
Value::Array(arr) => {
let mut headers = Vec::new();
for (i, row) in arr.iter().enumerate() {
match row {
Value::Object(row) => {
if i == 0 {
for entry in row {
headers.push(entry.0);
}
} else {
for entry in row {
if !headers.contains(&entry.0) {
return Err(create_io_error(
"the json is not a fully valid tabular struct",
));
}
}
}
}
_ => return Err(create_io_error("the tabular row is not a object")),
}
}
let mut headers_row: Row = Row::new(vec![]);
for k in headers {
headers_row.values.push(str_to_basictypes(k.to_string()));
}
let mut rv = Tabular::new(headers_row.clone());
for row in arr {
let mut r = Row::new(vec![]);
for k in headers_row.to_csv_vec().iter() {
r.values.push(match row.get(k).unwrap() {
Value::String(s) => str_to_basictypes(s.to_string()),
Value::Number(s) => str_to_basictypes(format!("{}", s)),
Value::Bool(s) => str_to_basictypes(format!("{}", s)),
Value::Null => BasicTypes::Null,
_ => str_to_basictypes("".to_string()),
});
}
rv.add_row(r);
}
rv
}
_ => return Err(create_io_error("the json is not array")),
};
Ok(data)
}
pub fn write_json_object(path: &str, data: &Value, pretty: bool) -> Result<(), Error> {
let text: String;
if pretty {
text = serde_json::to_string_pretty(data)?;
} else {
text = serde_json::to_string(data)?;
}
write_file(path, &text)
}