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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
use crate::json::paths::ValuePaths;
use crate::json::ValueType;
use crate::Cli;
use super::IndexMap;
use dashmap::DashMap;
use rayon::iter::ParallelBridge;
use rayon::prelude::ParallelIterator;
pub use serde_json::Value;
use std::error::{self, Error};
use std::fs::File;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
use std::{
fmt,
io::{self, prelude::*},
};
#[derive(Debug, PartialEq, Default)]
pub struct FileStats {
pub keys_count: IndexMap<String, usize>,
pub line_count: usize,
pub bad_lines: Vec<usize>,
pub keys_types_count: IndexMap<String, usize>,
pub empty_lines: Vec<usize>,
}
impl FileStats {
pub fn new() -> FileStats {
FileStats {
keys_count: IndexMap::new(),
line_count: 0,
bad_lines: Vec::new(),
keys_types_count: IndexMap::new(),
empty_lines: Vec::new(),
}
}
pub fn key_occurance(&self) -> IndexMap<String, f64> {
self.keys_count
.iter()
.map(|(k, v)| (k.to_owned(), 100f64 * *v as f64 / self.line_count as f64))
.collect()
}
pub fn key_type_occurance(&self) -> IndexMap<String, f64> {
self.keys_types_count
.iter()
.map(|(k, v)| (k.to_owned(), 100f64 * *v as f64 / self.line_count as f64))
.collect()
}
}
impl fmt::Display for FileStats {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "Keys:\n{:#?}\n", self.keys_count.keys())?;
writeln!(f, "Key occurance counts:\n{:#?}", self.keys_count)?;
writeln!(f, "Key occurance rate:")?;
for (k, v) in self.key_occurance() {
writeln!(f, "{}: {}%", k, v)?;
}
writeln!(f, "Key type occurance rate:")?;
for (k, v) in self.key_type_occurance() {
writeln!(f, "{}: {}%", k, v)?;
}
writeln!(f, "Corrupted lines:\n{:?}", self.bad_lines)?;
writeln!(f, "Empty lines:\n{:?}", self.empty_lines)
}
}
fn until_err<T, E>(err: &mut &mut Result<(), E>, item: Result<T, E>) -> Option<T> {
match item {
Ok(item) => Some(item),
Err(e) => {
**err = Err(e);
None
}
}
}
pub fn parse_json_iterable<E: 'static + Error>(
args: &Cli,
json_iter: impl IntoIterator<Item = Result<String, E>>,
) -> Result<FileStats, Box<dyn error::Error>> {
let mut fs = FileStats::new();
let json_iter = parse_iter(args, json_iter);
let jsonpath = args.jsonpath_selector()?;
for (i, json_candidate) in json_iter.enumerate() {
let json_candidate = json_candidate?;
let iter_number = i + 1;
fs.line_count = iter_number;
let mut json: Value = match serde_json::from_str(&json_candidate) {
Ok(v) => v,
Err(_) => {
fs.bad_lines.push(iter_number);
continue;
}
};
if let Some(ref selector) = jsonpath {
let mut json_list = selector.find(&json);
if let Some(json_1) = json_list.next() {
assert_eq!(None, json_list.next());
json = json_1.to_owned()
} else {
fs.empty_lines.push(iter_number);
continue;
}
}
for value_path in json.value_paths(args.explode_arrays) {
let path = value_path.jsonpath();
let counter = fs.keys_count.entry(path.to_owned()).or_insert(0);
*counter += 1;
let type_ = value_path.value.value_type();
let path_type = format!("{}::{}", path, type_);
let counter = fs.keys_types_count.entry(path_type).or_insert(0);
*counter += 1;
}
}
Ok(fs)
}
pub fn parse_json_iterable_par<E>(
args: &Cli,
json_iter: impl Iterator<Item = Result<String, E>> + Send,
) -> Result<FileStats, Box<dyn error::Error>>
where
E: 'static + Error + Send,
{
let keys_count: DashMap<String, usize> = DashMap::new();
let keys_types_count: DashMap<String, usize> = DashMap::new();
let mut bad_lines: Vec<usize> = Vec::new();
let bad_lines_mutex = Mutex::new(&mut bad_lines);
let line_count = AtomicUsize::new(0);
let mut empty_lines: Vec<usize> = Vec::new();
let empty_lines_mutex = Mutex::new(&mut empty_lines);
let json_iter = parse_iter(args, json_iter);
let jsonpath = args.jsonpath_selector()?;
let mut err = Ok(());
let json_iter = json_iter.scan(&mut err, until_err);
json_iter
.enumerate()
.par_bridge()
.map(|(i, json_candidate)| (i, serde_json::from_str(&json_candidate)))
.inspect(|(i, j): &(usize, Result<Value, serde_json::Error>)| {
let line_num = i + 1;
if j.is_err() {
let mut bad_lines = bad_lines_mutex.lock().unwrap();
bad_lines.push(line_num);
}
line_count.fetch_max(line_num, Ordering::Release);
})
.filter(|(_i, j)| j.is_ok())
.map(|(i, j)| (i, j.unwrap()))
.for_each(|(i, mut json)| {
let mut continue_ = false;
if let Some(ref selector) = jsonpath {
let mut json_list = selector.find(&json);
if let Some(json_1) = json_list.next() {
assert_eq!(None, json_list.next());
json = json_1.to_owned()
} else {
let line_num = i + 1;
let mut empty_lines = empty_lines_mutex.lock().unwrap();
empty_lines.push(line_num);
continue_ = true;
}
}
if !continue_ {
for value_path in json.value_paths(args.explode_arrays) {
let path = value_path.jsonpath();
let mut counter = keys_count.entry(path.to_owned()).or_insert(0);
*counter.value_mut() += 1;
let type_ = value_path.value.value_type();
let path_type = format!("{}::{}", path, type_);
let mut counter = keys_types_count.entry(path_type).or_insert(0);
*counter.value_mut() += 1;
}
}
});
err?;
let fs = FileStats {
keys_count: keys_count
.into_read_only()
.iter()
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.collect(),
line_count: line_count.load(Ordering::Acquire),
keys_types_count: keys_types_count
.into_read_only()
.iter()
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.collect(),
bad_lines,
empty_lines,
};
Ok(fs)
}
pub fn parse_iter<E, I>(args: &Cli, iter: I) -> impl Iterator<Item = Result<String, E>>
where
I: IntoIterator<Item = Result<String, E>>,
{
let iter = iter.into_iter();
if let Some(n) = args.lines {
iter.take(n)
} else {
iter.take(usize::MAX)
}
}
pub fn parse_ndjson_bufreader(
args: &Cli,
bufreader: impl BufRead + Send,
) -> Result<FileStats, Box<dyn error::Error>> {
let json_iter = bufreader.lines();
parse_json_iterable_par(args, json_iter)
}
pub fn parse_ndjson_file(args: &Cli, file: File) -> Result<FileStats, Box<dyn error::Error>> {
parse_ndjson_bufreader(args, io::BufReader::new(file))
}
pub trait Paths {
fn paths(&self) -> Vec<String>;
}
impl Paths for Value {
fn paths(&self) -> Vec<String> {
super::paths::parse_json_paths(self)
}
}
pub trait PathTypes {
fn path_types(&self) -> IndexMap<String, String>;
}
impl PathTypes for Value {
fn path_types(&self) -> IndexMap<String, String> {
super::paths::parse_json_paths_types(self)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
use std::io::{Seek, SeekFrom, Write};
#[test]
fn simple_ndjson_file() {
let mut tmpfile: File = tempfile::tempfile().unwrap();
writeln!(tmpfile, r#"{{"key1": 123}}"#).unwrap();
writeln!(tmpfile, r#"{{"key2": 123}}"#).unwrap();
writeln!(tmpfile, r#"{{"key1": 123}}"#).unwrap();
tmpfile.seek(SeekFrom::Start(0)).unwrap();
let expected = FileStats {
keys_count: [("$.key1".to_string(), 2), ("$.key2".to_string(), 1)]
.iter()
.cloned()
.collect(),
line_count: 3,
keys_types_count: [
("$.key1::Number".to_string(), 2),
("$.key2::Number".to_string(), 1),
]
.iter()
.cloned()
.collect(),
..Default::default()
};
let args = Cli::default();
let file_stats = parse_ndjson_file(&args, tmpfile).unwrap();
assert_eq!(expected, file_stats);
}
#[test]
fn simple_ndjson_iterable() {
let iter: Vec<Result<String, std::io::Error>> = vec![
Ok(r#"{"key1": 123}"#.to_string()),
Ok(r#"{"key2": 123}"#.to_string()),
Ok(r#"{"key1": 123}"#.to_string()),
];
let iter = iter.into_iter();
let expected = FileStats {
keys_count: [("$.key1".to_string(), 2), ("$.key2".to_string(), 1)]
.iter()
.cloned()
.collect(),
line_count: 3,
keys_types_count: [
("$.key1::Number".to_string(), 2),
("$.key2::Number".to_string(), 1),
]
.iter()
.cloned()
.collect(),
..Default::default()
};
let args = Cli::default();
let file_stats = parse_json_iterable(&args, iter).unwrap();
assert_eq!(expected, file_stats);
}
#[test]
fn simple_ndjson_iterable_par() {
let iter: Vec<Result<String, std::io::Error>> = vec![
Ok(r#"{"key1": 123}"#.to_string()),
Ok(r#"{"key2": 123}"#.to_string()),
Ok(r#"{"key1": 123}"#.to_string()),
];
let iter = iter.into_iter();
let expected = FileStats {
keys_count: [("$.key1".to_string(), 2), ("$.key2".to_string(), 1)]
.iter()
.cloned()
.collect(),
line_count: 3,
keys_types_count: [
("$.key1::Number".to_string(), 2),
("$.key2::Number".to_string(), 1),
]
.iter()
.cloned()
.collect(),
..Default::default()
};
let args = Cli::default();
let file_stats = parse_json_iterable_par(&args, iter).unwrap();
assert_eq!(expected, file_stats);
}
#[test]
fn bad_ndjson_file() {
let mut tmpfile: File = tempfile::tempfile().unwrap();
writeln!(tmpfile, "{{").unwrap();
tmpfile.seek(SeekFrom::Start(0)).unwrap();
let expected = FileStats {
bad_lines: vec![1],
line_count: 1,
..Default::default()
};
let args = Cli::default();
let file_stats = parse_ndjson_file(&args, tmpfile).unwrap();
assert_eq!(expected, file_stats);
}
#[test]
fn simple_ndjson_iterable_jsonpath() {
let iter: Vec<Result<String, std::io::Error>> = vec![
Ok(r#"{"key1": 123}"#.to_string()),
Ok(r#"{"a": {"key2": 123}}"#.to_string()),
Ok(r#"{"key1": 123}"#.to_string()),
];
let iter = iter.into_iter();
let expected = FileStats {
keys_count: [("$.key2".to_string(), 1)].iter().cloned().collect(),
line_count: 3,
keys_types_count: [("$.key2::Number".to_string(), 1)]
.iter()
.cloned()
.collect(),
empty_lines: vec![1, 3],
..Default::default()
};
let mut args = Cli::default();
args.jsonpath = Some("$.a".to_string());
let file_stats = parse_json_iterable(&args, iter).unwrap();
assert_eq!(expected, file_stats);
}
#[test]
fn simple_ndjson_iterable_par_jsonpath() {
let iter: Vec<Result<String, std::io::Error>> = vec![
Ok(r#"{"key1": 123}"#.to_string()),
Ok(r#"{"a": {"key2": 123}}"#.to_string()),
Ok(r#"{"key1": 123}"#.to_string()),
];
let iter = iter.into_iter();
let expected = FileStats {
keys_count: [("$.key2".to_string(), 1)].iter().cloned().collect(),
line_count: 3,
keys_types_count: [("$.key2::Number".to_string(), 1)]
.iter()
.cloned()
.collect(),
empty_lines: vec![1, 3],
..Default::default()
};
let mut args = Cli::default();
args.jsonpath = Some("$.a".to_string());
let file_stats = parse_json_iterable_par(&args, iter).unwrap();
assert_eq!(expected, file_stats);
}
}