jpx-core 0.2.2

Complete JMESPath implementation with 400+ extension functions
Documentation
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
//! CSV and TSV formatting functions.

use std::collections::HashSet;

use csv::WriterBuilder;
use serde_json::Value;

use crate::functions::{Function, custom_error};
use crate::interpreter::SearchResult;
use crate::registry::register_if_enabled;
use crate::{Context, Runtime, arg, defn};

/// Convert a serde_json::Value to a string suitable for CSV field.
fn value_to_csv_string(value: &Value) -> String {
    match value {
        Value::Null => String::new(),
        Value::Bool(b) => b.to_string(),
        Value::Number(n) => n.to_string(),
        Value::String(s) => s.clone(),
        Value::Array(_) | Value::Object(_) => serde_json::to_string(value).unwrap_or_default(),
    }
}

/// Write a single row using the csv crate's writer.
fn write_csv_row(fields: &[String], delimiter: u8) -> Result<String, std::io::Error> {
    let mut wtr = WriterBuilder::new()
        .delimiter(delimiter)
        .has_headers(false)
        .from_writer(vec![]);

    wtr.write_record(fields)?;
    wtr.flush()?;

    let data = wtr
        .into_inner()
        .map_err(|e| std::io::Error::other(e.to_string()))?;

    let mut s = String::from_utf8(data).unwrap_or_default();
    if s.ends_with('\n') {
        s.pop();
    }
    if s.ends_with('\r') {
        s.pop();
    }
    Ok(s)
}

/// Write multiple rows using the csv crate's writer.
fn write_csv_rows(rows: &[Vec<String>], delimiter: u8) -> Result<String, std::io::Error> {
    let mut wtr = WriterBuilder::new()
        .delimiter(delimiter)
        .has_headers(false)
        .from_writer(vec![]);

    for row in rows {
        wtr.write_record(row)?;
    }
    wtr.flush()?;

    let data = wtr
        .into_inner()
        .map_err(|e| std::io::Error::other(e.to_string()))?;

    let mut s = String::from_utf8(data).unwrap_or_default();
    if s.ends_with('\n') {
        s.pop();
    }
    if s.ends_with('\r') {
        s.pop();
    }
    Ok(s)
}

// =============================================================================
// to_csv(array) -> string
// =============================================================================

defn!(ToCsvFn, vec![arg!(array)], None);

impl Function for ToCsvFn {
    fn evaluate(&self, args: &[Value], ctx: &mut Context<'_>) -> SearchResult {
        self.signature.validate(args, ctx)?;

        let arr = args[0].as_array().unwrap();

        if arr.is_empty() {
            return Ok(Value::String(String::new()));
        }

        let fields: Vec<String> = arr.iter().map(value_to_csv_string).collect();

        match write_csv_row(&fields, b',') {
            Ok(s) => Ok(Value::String(s)),
            Err(e) => Err(custom_error(ctx, &format!("CSV write error: {}", e))),
        }
    }
}

// =============================================================================
// to_tsv(array) -> string
// =============================================================================

defn!(ToTsvFn, vec![arg!(array)], None);

impl Function for ToTsvFn {
    fn evaluate(&self, args: &[Value], ctx: &mut Context<'_>) -> SearchResult {
        self.signature.validate(args, ctx)?;

        let arr = args[0].as_array().unwrap();

        if arr.is_empty() {
            return Ok(Value::String(String::new()));
        }

        let fields: Vec<String> = arr.iter().map(value_to_csv_string).collect();

        match write_csv_row(&fields, b'\t') {
            Ok(s) => Ok(Value::String(s)),
            Err(e) => Err(custom_error(ctx, &format!("TSV write error: {}", e))),
        }
    }
}

// =============================================================================
// to_csv_rows(array_of_arrays) -> string
// =============================================================================

defn!(ToCsvRowsFn, vec![arg!(array)], None);

impl Function for ToCsvRowsFn {
    fn evaluate(&self, args: &[Value], ctx: &mut Context<'_>) -> SearchResult {
        self.signature.validate(args, ctx)?;

        let rows_var = args[0].as_array().unwrap();

        if rows_var.is_empty() {
            return Ok(Value::String(String::new()));
        }

        let rows: Vec<Vec<String>> = rows_var
            .iter()
            .map(|row| {
                if let Some(arr) = row.as_array() {
                    arr.iter().map(value_to_csv_string).collect()
                } else {
                    vec![value_to_csv_string(row)]
                }
            })
            .collect();

        match write_csv_rows(&rows, b',') {
            Ok(s) => Ok(Value::String(s)),
            Err(e) => Err(custom_error(ctx, &format!("CSV write error: {}", e))),
        }
    }
}

// =============================================================================
// to_csv_table(array_of_objects, columns?) -> string
// =============================================================================

defn!(ToCsvTableFn, vec![arg!(array)], Some(arg!(array)));

impl Function for ToCsvTableFn {
    fn evaluate(&self, args: &[Value], ctx: &mut Context<'_>) -> SearchResult {
        self.signature.validate(args, ctx)?;

        let rows = args[0].as_array().unwrap();

        if rows.is_empty() {
            return Ok(Value::String(String::new()));
        }

        // Determine columns: from second argument or from first object's keys
        let columns: Vec<String> = if args.len() > 1 {
            args[1]
                .as_array()
                .unwrap()
                .iter()
                .filter_map(|v| v.as_str().map(|s| s.to_string()))
                .collect()
        } else if let Some(obj) = rows[0].as_object() {
            let mut keys: Vec<String> = obj.keys().cloned().collect();
            keys.sort();
            keys
        } else {
            return Ok(Value::String(String::new()));
        };

        if columns.is_empty() {
            return Ok(Value::String(String::new()));
        }

        let mut all_rows: Vec<Vec<String>> = Vec::with_capacity(rows.len() + 1);

        // Header row
        all_rows.push(columns.clone());

        // Data rows
        for row in rows.iter() {
            if let Some(obj) = row.as_object() {
                let data_row: Vec<String> = columns
                    .iter()
                    .map(|col| obj.get(col).map(value_to_csv_string).unwrap_or_default())
                    .collect();
                all_rows.push(data_row);
            } else {
                all_rows.push(columns.iter().map(|_| String::new()).collect());
            }
        }

        match write_csv_rows(&all_rows, b',') {
            Ok(s) => Ok(Value::String(s)),
            Err(e) => Err(custom_error(ctx, &format!("CSV write error: {}", e))),
        }
    }
}

// =============================================================================
// from_csv(string) -> array of arrays
// =============================================================================

defn!(FromCsvFn, vec![arg!(string)], None);

impl Function for FromCsvFn {
    fn evaluate(&self, args: &[Value], ctx: &mut Context<'_>) -> SearchResult {
        self.signature.validate(args, ctx)?;
        let input = args[0].as_str().unwrap();
        parse_delimited(input, b',', ctx)
    }
}

// =============================================================================
// from_tsv(string) -> array of arrays
// =============================================================================

defn!(FromTsvFn, vec![arg!(string)], None);

impl Function for FromTsvFn {
    fn evaluate(&self, args: &[Value], ctx: &mut Context<'_>) -> SearchResult {
        self.signature.validate(args, ctx)?;
        let input = args[0].as_str().unwrap();
        parse_delimited(input, b'\t', ctx)
    }
}

/// Parse a delimited string (CSV or TSV) into an array of arrays.
fn parse_delimited(input: &str, delimiter: u8, ctx: &Context<'_>) -> SearchResult {
    use csv::ReaderBuilder;

    if input.trim().is_empty() {
        return Ok(Value::Array(vec![]));
    }

    let mut reader = ReaderBuilder::new()
        .delimiter(delimiter)
        .has_headers(false)
        .flexible(true)
        .from_reader(input.as_bytes());

    let mut rows: Vec<Value> = Vec::new();

    for result in reader.records() {
        match result {
            Ok(record) => {
                let row: Vec<Value> = record
                    .iter()
                    .map(|field| Value::String(field.to_string()))
                    .collect();
                rows.push(Value::Array(row));
            }
            Err(e) => {
                return Err(custom_error(ctx, &format!("CSV parse error: {}", e)));
            }
        }
    }

    Ok(Value::Array(rows))
}

/// Register format functions filtered by the enabled set.
pub fn register_filtered(runtime: &mut Runtime, enabled: &HashSet<&str>) {
    register_if_enabled(runtime, "to_csv", enabled, Box::new(ToCsvFn::new()));
    register_if_enabled(runtime, "to_tsv", enabled, Box::new(ToTsvFn::new()));
    register_if_enabled(
        runtime,
        "to_csv_rows",
        enabled,
        Box::new(ToCsvRowsFn::new()),
    );
    register_if_enabled(
        runtime,
        "to_csv_table",
        enabled,
        Box::new(ToCsvTableFn::new()),
    );
    register_if_enabled(runtime, "from_csv", enabled, Box::new(FromCsvFn::new()));
    register_if_enabled(runtime, "from_tsv", enabled, Box::new(FromTsvFn::new()));
}

#[cfg(test)]
mod tests {
    use crate::Runtime;
    use serde_json::json;

    fn setup_runtime() -> Runtime {
        Runtime::builder()
            .with_standard()
            .with_all_extensions()
            .build()
    }

    // =========================================================================
    // to_csv tests
    // =========================================================================

    #[test]
    fn test_to_csv_simple() {
        let runtime = setup_runtime();
        let expr = runtime.compile("to_csv(@)").unwrap();
        let data = json!(["a", "b", "c"]);
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_str().unwrap(), "a,b,c");
    }

    #[test]
    fn test_to_csv_mixed_types() {
        let runtime = setup_runtime();
        let expr = runtime.compile("to_csv(@)").unwrap();
        let data = json!(["hello", 42, true, null]);
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_str().unwrap(), "hello,42,true,");
    }

    #[test]
    fn test_to_csv_with_comma() {
        let runtime = setup_runtime();
        let expr = runtime.compile("to_csv(@)").unwrap();
        let data = json!(["hello, world", "test"]);
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_str().unwrap(), "\"hello, world\",test");
    }

    #[test]
    fn test_to_csv_with_quotes() {
        let runtime = setup_runtime();
        let expr = runtime.compile("to_csv(@)").unwrap();
        let data = json!(["say \"hello\"", "test"]);
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_str().unwrap(), "\"say \"\"hello\"\"\",test");
    }

    #[test]
    fn test_to_csv_with_newline() {
        let runtime = setup_runtime();
        let expr = runtime.compile("to_csv(@)").unwrap();
        let data = json!(["line1\nline2", "test"]);
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_str().unwrap(), "\"line1\nline2\",test");
    }

    #[test]
    fn test_to_csv_empty() {
        let runtime = setup_runtime();
        let expr = runtime.compile("to_csv(@)").unwrap();
        let data = json!([]);
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_str().unwrap(), "");
    }

    #[test]
    fn test_to_csv_with_leading_trailing_space() {
        let runtime = setup_runtime();
        let expr = runtime.compile("to_csv(@)").unwrap();
        let data = json!(["  hello  ", "test"]);
        let result = expr.search(&data).unwrap();
        // csv crate quotes fields with leading/trailing whitespace to preserve them
        assert!(result.as_str().unwrap().contains("hello"));
    }

    // =========================================================================
    // to_tsv tests
    // =========================================================================

    #[test]
    fn test_to_tsv_simple() {
        let runtime = setup_runtime();
        let expr = runtime.compile("to_tsv(@)").unwrap();
        let data = json!(["a", "b", "c"]);
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_str().unwrap(), "a\tb\tc");
    }

    #[test]
    fn test_to_tsv_mixed_types() {
        let runtime = setup_runtime();
        let expr = runtime.compile("to_tsv(@)").unwrap();
        let data = json!(["hello", 42, true, null]);
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_str().unwrap(), "hello\t42\ttrue\t");
    }

    // =========================================================================
    // to_csv_rows tests
    // =========================================================================

    #[test]
    fn test_to_csv_rows_simple() {
        let runtime = setup_runtime();
        let expr = runtime.compile("to_csv_rows(@)").unwrap();
        let data = json!([[1, 2, 3], [4, 5, 6]]);
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_str().unwrap(), "1,2,3\n4,5,6");
    }

    #[test]
    fn test_to_csv_rows_with_strings() {
        let runtime = setup_runtime();
        let expr = runtime.compile("to_csv_rows(@)").unwrap();
        let data = json!([["a", "b"], ["c", "d"]]);
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_str().unwrap(), "a,b\nc,d");
    }

    #[test]
    fn test_to_csv_rows_empty() {
        let runtime = setup_runtime();
        let expr = runtime.compile("to_csv_rows(@)").unwrap();
        let data = json!([]);
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_str().unwrap(), "");
    }

    #[test]
    fn test_to_csv_rows_with_special_chars() {
        let runtime = setup_runtime();
        let expr = runtime.compile("to_csv_rows(@)").unwrap();
        let data = json!([["hello, world", "test"], ["a\"b", "c"]]);
        let result = expr.search(&data).unwrap();
        // Should properly escape commas and quotes
        assert!(result.as_str().unwrap().contains("\"hello, world\""));
        assert!(result.as_str().unwrap().contains("\"a\"\"b\""));
    }

    // =========================================================================
    // to_csv_table tests
    // =========================================================================

    #[test]
    fn test_to_csv_table_simple() {
        let runtime = setup_runtime();
        let expr = runtime.compile("to_csv_table(@)").unwrap();
        let data = json!([{"name": "alice", "age": 30}, {"name": "bob", "age": 25}]);
        let result = expr.search(&data).unwrap();
        // Keys are sorted alphabetically
        assert_eq!(result.as_str().unwrap(), "age,name\n30,alice\n25,bob");
    }

    #[test]
    fn test_to_csv_table_with_columns() {
        let runtime = setup_runtime();
        let expr = runtime
            .compile("to_csv_table(@, `[\"name\", \"age\"]`)")
            .unwrap();
        let data = json!([{"name": "alice", "age": 30}, {"name": "bob", "age": 25}]);
        let result = expr.search(&data).unwrap();
        // Columns in specified order
        assert_eq!(result.as_str().unwrap(), "name,age\nalice,30\nbob,25");
    }

    #[test]
    fn test_to_csv_table_missing_field() {
        let runtime = setup_runtime();
        let expr = runtime
            .compile("to_csv_table(@, `[\"name\", \"age\", \"email\"]`)")
            .unwrap();
        let data = json!([{"name": "alice", "age": 30}, {"name": "bob"}]);
        let result = expr.search(&data).unwrap();
        // Missing fields are empty
        assert_eq!(result.as_str().unwrap(), "name,age,email\nalice,30,\nbob,,");
    }

    #[test]
    fn test_to_csv_table_empty() {
        let runtime = setup_runtime();
        let expr = runtime.compile("to_csv_table(@)").unwrap();
        let data = json!([]);
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_str().unwrap(), "");
    }

    #[test]
    fn test_to_csv_table_special_chars() {
        let runtime = setup_runtime();
        let expr = runtime.compile("to_csv_table(@)").unwrap();
        let data = json!([{"name": "O'Brien, Jr.", "note": "said \"hi\""}]);
        let result = expr.search(&data).unwrap();
        // Should properly escape commas and quotes
        assert!(result.as_str().unwrap().contains("\"O'Brien, Jr.\""));
        assert!(result.as_str().unwrap().contains("\"said \"\"hi\"\"\""));
    }

    // =========================================================================
    // from_csv tests
    // =========================================================================

    #[test]
    fn test_from_csv_simple() {
        let runtime = setup_runtime();
        let data = json!({"csv": "a,b,c\n1,2,3"});
        let expr = runtime.compile("from_csv(csv)").unwrap();
        let result = expr.search(&data).unwrap();
        let arr = result.as_array().unwrap();
        assert_eq!(arr.len(), 2);
        // First row
        let row0 = arr[0].as_array().unwrap();
        assert_eq!(row0[0].as_str().unwrap(), "a");
        assert_eq!(row0[1].as_str().unwrap(), "b");
        assert_eq!(row0[2].as_str().unwrap(), "c");
        // Second row
        let row1 = arr[1].as_array().unwrap();
        assert_eq!(row1[0].as_str().unwrap(), "1");
        assert_eq!(row1[1].as_str().unwrap(), "2");
        assert_eq!(row1[2].as_str().unwrap(), "3");
    }

    #[test]
    fn test_from_csv_quoted() {
        let runtime = setup_runtime();
        let data = json!({"csv": "\"hello, world\",test"});
        let expr = runtime.compile("from_csv(csv)").unwrap();
        let result = expr.search(&data).unwrap();
        let arr = result.as_array().unwrap();
        assert_eq!(arr.len(), 1);
        let row0 = arr[0].as_array().unwrap();
        assert_eq!(row0[0].as_str().unwrap(), "hello, world");
        assert_eq!(row0[1].as_str().unwrap(), "test");
    }

    #[test]
    fn test_from_csv_empty() {
        let runtime = setup_runtime();
        let data = json!({"csv": ""});
        let expr = runtime.compile("from_csv(csv)").unwrap();
        let result = expr.search(&data).unwrap();
        let arr = result.as_array().unwrap();
        assert_eq!(arr.len(), 0);
    }

    #[test]
    fn test_from_csv_single_row() {
        let runtime = setup_runtime();
        let data = json!({"csv": "a,b,c"});
        let expr = runtime.compile("from_csv(csv)").unwrap();
        let result = expr.search(&data).unwrap();
        let arr = result.as_array().unwrap();
        assert_eq!(arr.len(), 1);
        let row0 = arr[0].as_array().unwrap();
        assert_eq!(row0.len(), 3);
    }

    // =========================================================================
    // from_tsv tests
    // =========================================================================

    #[test]
    fn test_from_tsv_simple() {
        let runtime = setup_runtime();
        let data = json!({"tsv": "a\tb\tc\n1\t2\t3"});
        let expr = runtime.compile("from_tsv(tsv)").unwrap();
        let result = expr.search(&data).unwrap();
        let arr = result.as_array().unwrap();
        assert_eq!(arr.len(), 2);
        // First row
        let row0 = arr[0].as_array().unwrap();
        assert_eq!(row0[0].as_str().unwrap(), "a");
        assert_eq!(row0[1].as_str().unwrap(), "b");
        assert_eq!(row0[2].as_str().unwrap(), "c");
    }

    #[test]
    fn test_from_tsv_empty() {
        let runtime = setup_runtime();
        let data = json!({"tsv": ""});
        let expr = runtime.compile("from_tsv(tsv)").unwrap();
        let result = expr.search(&data).unwrap();
        let arr = result.as_array().unwrap();
        assert_eq!(arr.len(), 0);
    }

    #[test]
    fn test_from_tsv_spaces_preserved() {
        let runtime = setup_runtime();
        let data = json!({"tsv": "hello world\ttest"});
        let expr = runtime.compile("from_tsv(tsv)").unwrap();
        let result = expr.search(&data).unwrap();
        let arr = result.as_array().unwrap();
        let row0 = arr[0].as_array().unwrap();
        assert_eq!(row0[0].as_str().unwrap(), "hello world");
        assert_eq!(row0[1].as_str().unwrap(), "test");
    }

    // =========================================================================
    // roundtrip tests
    // =========================================================================

    #[test]
    fn test_csv_roundtrip() {
        let runtime = setup_runtime();
        // to_csv_rows then from_csv should give back similar structure
        let data = json!([["a", "b"], ["1", "2"]]);
        let expr = runtime.compile("to_csv_rows(@)").unwrap();
        let csv_result = expr.search(&data).unwrap();

        // Now parse it back
        let parse_data = json!({"csv": csv_result.as_str().unwrap()});
        let parse_expr = runtime.compile("from_csv(csv)").unwrap();
        let parsed = parse_expr.search(&parse_data).unwrap();

        let arr = parsed.as_array().unwrap();
        assert_eq!(arr.len(), 2);
        let row0 = arr[0].as_array().unwrap();
        assert_eq!(row0[0].as_str().unwrap(), "a");
        assert_eq!(row0[1].as_str().unwrap(), "b");
    }
}