json_keyquotes_convert 0.2.3

A Rust library crate to convert JSON from and to JSON without key-quotes.
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
//! Core functions used for the JSON conversions.
//!
//! Contains the core functionality of this crate.

use std::path::Path;

use once_cell::sync::Lazy;
use regex::Regex;

use crate::{load_write_utils, Quotes};

const SUPPORTED_KEY_CHARS_REGEX_STR: &str = r#"A-Za-z0-9`~!@#$%€^&*()\-_=+\\|;"'.<>/?\s"#;

/// Convenience method for chained [load_write_utils::load_json],
/// [json_remove_key_quotes], [json_unescape_ctrlchars]
///  and [load_write_utils::write_json] function calls.
///
/// # Arguments
///
/// * `path` - The file path.
///
/// # Examples
///
/// ```rust,ignore
/// use std::path::Path;
/// use json_keyquotes_convert::{json_key_quote_utils};
///
/// let path = Path::new("./test_resources/Test_with_keyquotes.json");
/// json_key_quote_utils::json_convert_with_to_without_keyquotes(path);
/// ```
pub fn json_convert_with_to_without_keyquotes(path: &Path) {
    let json = match load_write_utils::load_json(path) {
        Ok(val) => val,
        Err(err) => {
            eprintln!("{}", err);
            return;
        }
    };

    let unquoted_json = json_remove_key_quotes(&json);

    match load_write_utils::write_json(path, &json_unescape_ctrlchars(&unquoted_json)) {
        Ok(()) => (),
        Err(err) => {
            eprintln!("{}", err);
            return;
        }
    }
}

/// Convenience method for chained [load_write_utils::load_json], [json_add_key_quotes]
/// ,[json_escape_ctrlchars] and [load_write_utils::write_json] calls.
///
/// # Arguments
///
/// * `path` - The file path.
/// * `quote_type` - Whether the JSON keys should be single- or double-quoted.
///
/// # Examples
///
/// ```rust,ignore
/// use std::path::Path;
/// use json_keyquotes_convert::{json_keyquote_utils, Quotes};
///
/// let path = Path::new("./test_resources/Test_without_keyquotes.json")
/// json_keyquote_utils::json_convert_without_to_with_keyquotes(path, Quotes::default());
/// ```
pub fn json_convert_without_to_with_keyquotes(path: &Path, quote_type: Quotes) {
    let json = match load_write_utils::load_json(path) {
        Ok(val) => val,
        Err(err) => {
            eprintln!("{}", err);
            return;
        }
    };

    let keyquoted_json = json_add_key_quotes(&json, quote_type);

    match load_write_utils::write_json(path, &json_escape_ctrlchars(&keyquoted_json)) {
        Ok(()) => (),
        Err(err) => {
            eprintln!("{}", err);
            return;
        }
    }
}

/// Adds key-quotes to the JSON string.
///
/// # Arguments
///
/// * `json` - The JSON string.
/// * `quote_type` - Whether the JSON keys should be single- or double-quoted.
///
/// # Examples
///
/// ```
/// use json_keyquotes_convert::{json_key_quote_utils, Quotes};
///
/// let json_added = json_key_quote_utils::json_add_key_quotes("{key: \"val\"}", Quotes::default());
/// assert_eq!(json_added, "{\"key\": \"val\"}");
///
/// let json_already_existing = json_key_quote_utils::json_add_key_quotes("{\"key\": \"val\"}", Quotes::default());
/// assert_eq!(json_already_existing, "{\"key\": \"val\"}");
/// ```
pub fn json_add_key_quotes(json: &str, quote_type: Quotes) -> String {
    // Add quotes around all string keys (single-quoted):
    // `/` == `\/` in Regex101
    let single_quoted_string_val_regex = Lazy::new(|| {
        Regex::new(
            &(r#"(?P<prevchar_key>[^"'][\s]*)(?P<key>["#.to_string()
                + SUPPORTED_KEY_CHARS_REGEX_STR
                + r#"]*?[^"'])(?P<val>:\s*?'[\s\S]*?')"#),
        )
        .unwrap()
    });
    let json_single_quoted_string_passed = single_quoted_string_val_regex.replace_all(
        json,
        "$prevchar_key".to_string() + quote_type.as_str() + "$key" + quote_type.as_str() + "$val",
    );

    // Add quotes around all string keys (double-quoted):
    // `/` == `\/` in Regex101
    let double_quoted_string_val_regex = Lazy::new(|| {
        Regex::new(
            &(r#"(?P<prevchar_key>[^"'][\s]*)(?P<key>["#.to_string()
                + SUPPORTED_KEY_CHARS_REGEX_STR
                + r#"]*?[^"'])(?P<val>:\s*?"[\s\S]*?")"#),
        )
        .unwrap()
    });
    let json_double_quoted_string_passed = double_quoted_string_val_regex.replace_all(
        &json_single_quoted_string_passed,
        "$prevchar_key".to_string() + quote_type.as_str() + "$key" + quote_type.as_str() + "$val",
    );

    // Add quotes around all object keys:
    // `/` == `\/` in Regex101
    let object_val_regex = Lazy::new(|| {
        Regex::new(
            &(r#"(?P<key>["#.to_string()
                + SUPPORTED_KEY_CHARS_REGEX_STR
                + r#"]*?[^"'])(?P<val>:\s*?[{\[])"#),
        )
        .unwrap()
    });
    let json_object_passed = object_val_regex.replace_all(
        &json_double_quoted_string_passed,
        quote_type.as_str().to_string() + "$key" + quote_type.as_str() + "$val",
    );

    // Add quotes around all number keys:
    // `/` == `\/` in Regex101
    let number_val_regex = Lazy::new(|| {
        Regex::new(
            &(r#"(?P<before>[\[,{]\s*?)(?P<key>["#.to_string()
                + SUPPORTED_KEY_CHARS_REGEX_STR
                + r#"]*?[^"'])(?P<after>:\s*?[\d\-\.])"#),
        )
        .unwrap()
    });
    let json_number_passed = number_val_regex.replace_all(
        &json_object_passed,
        "$before".to_string() + quote_type.as_str() + "$key" + quote_type.as_str() + "$after",
    );

    // Add quotes around all `null`, and `boolean` keys:
    // `/` == `\/` in Regex101
    let null_bools_val_regex = Lazy::new(|| {
        Regex::new(
            &(r#"(?P<before>[\[,{]\s*?)(?P<key>["#.to_string()
                + SUPPORTED_KEY_CHARS_REGEX_STR
                + r#"]*?[^"'])(?P<after>:\s*?(?:null|true|false))"#),
        )
        .unwrap()
    });
    let json_null_bools_passed = null_bools_val_regex.replace_all(
        &json_number_passed,
        "$before".to_string() + quote_type.as_str() + "$key" + quote_type.as_str() + "$after",
    );

    return json_null_bools_passed.to_string();
}

/// Removes key-quotes from the JSON string.
///
/// # Arguments
///
/// * `json` - The JSON string.
///
/// # Examples
///
/// ```
/// use json_keyquotes_convert::{json_key_quote_utils, Quotes};
///
/// let json_removed = json_key_quote_utils::json_remove_key_quotes("{\"key\": \"val\"}");
/// assert_eq!(json_removed, "{key: \"val\"}");
///
/// let json_already_removed = json_key_quote_utils::json_remove_key_quotes("{key: \"val\"}");
/// assert_eq!(json_already_removed, "{key: \"val\"}");
/// ```
pub fn json_remove_key_quotes(json: &str) -> String {
    // Remove the quotes from the keys (single-quoted):
    // `/` == `\/` in Regex101
    let single_quotes_regex = Lazy::new(|| {
        Regex::new(
            &(r#"(?P<before>[{\[,][\s]*)'(?P<key>["#.to_string()
                + SUPPORTED_KEY_CHARS_REGEX_STR
                + r#"]*?)'(?P<after>\s*?:)"#),
        )
        .unwrap()
    });
    let json_single_quotes_passed = single_quotes_regex.replace_all(json, "$before$key$after");

    // Remove the quotes from the keys (double-quoted):
    // `/` == `\/` in Regex101
    let double_quotes_regex = Lazy::new(|| {
        Regex::new(
            &(r#"(?P<before>[{\[,][\s]*)"(?P<key>["#.to_string()
                + SUPPORTED_KEY_CHARS_REGEX_STR
                + r#"]*?)"(?P<after>\s*?:)"#),
        )
        .unwrap()
    });
    let json_double_quotes_passed =
        double_quotes_regex.replace_all(&json_single_quotes_passed, "$before$key$after");

    return json_double_quotes_passed.to_string();
}

/// Escape ctrl-characters from the JSON string values
/// and remove ctrl-characters from the JSON keys with keyquotes.
///
/// This method will escape `newlines`, `tabs` and `carriage returns` in the JSON string values
/// and remove `newlines`, `tabs` and `carriage returns` in the JSON keys with keyquotes.
///
/// # Arguments
///
/// * `json` - The JSON string.
///
/// # Examples
///
/// ```
/// use json_keyquotes_convert::{json_key_quote_utils};
///
/// let json_escaped = json_key_quote_utils::json_escape_ctrlchars(r#"{"key": "va
/// l"}"#);
/// assert_eq!(json_escaped, r#"{"key": "va\nl"}"#);
///
/// let json_already_escaped = json_key_quote_utils::json_escape_ctrlchars(r#"{"key": "va\nl"}"#);
/// assert_eq!(json_already_escaped, r#"{"key": "va\nl"}"#);
/// ```
pub fn json_escape_ctrlchars(json: &str) -> String {
    // Replace all control characters with their escaped variants:

    let mut new_json = json.to_owned();

    // Two iterations are needed for the tab escaping:

    for _n in 0..2 {
        // For all single-quoted string keys with single-quoted values:
        let singlequoted_string_key_regex = Lazy::new(|| {
            Regex::new(
                &(r#"(?P<prevchar_key>[^"'][\s]*)'(?P<key>["#.to_string()
                    + SUPPORTED_KEY_CHARS_REGEX_STR
                    + r#"]*?[^"'])'(?P<val>\s*?:\s*?'[\s\S]*?')"#),
            )
            .unwrap()
        });
        for cap in singlequoted_string_key_regex.captures_iter(&new_json.clone()) {
            let cap_match = cap.name("key").unwrap().as_str();
            new_json = new_json.replacen(cap_match, &cap_match.replace("\n", ""), 1);
            new_json = new_json.replacen(cap_match, &cap_match.replace("\r", ""), 1);
            new_json =
                new_json.replacen(cap_match, &cap_match.replace("\t", "").replace("\t", ""), 1);
        }

        // For all double-quoted string keys with single-quoted values:
        let singlequoted_string_key_regex = Lazy::new(|| {
            Regex::new(
                &(r#"(?P<prevchar_key>[^"'][\s]*)"(?P<key>["#.to_string()
                    + SUPPORTED_KEY_CHARS_REGEX_STR
                    + r#"]*?[^"'])"(?P<val>\s*?:\s*?'[\s\S]*?')"#),
            )
            .unwrap()
        });
        for cap in singlequoted_string_key_regex.captures_iter(&new_json.clone()) {
            let cap_match = cap.name("key").unwrap().as_str();
            new_json = new_json.replacen(cap_match, &cap_match.replace("\n", ""), 1);
            new_json = new_json.replacen(cap_match, &cap_match.replace("\r", ""), 1);
            new_json =
                new_json.replacen(cap_match, &cap_match.replace("\t", "").replace("\t", ""), 1);
        }

        // For all single-quoted string keys with double-quoted values:
        let doublequoted_string_key_regex = Lazy::new(|| {
            Regex::new(
                &(r#"(?P<prevchar_key>[^"'][\s]*)'(?P<key>["#.to_string()
                    + SUPPORTED_KEY_CHARS_REGEX_STR
                    + r#"]*?[^"'])'(?P<val>\s*?:\s*?"[\s\S]*?")"#),
            )
            .unwrap()
        });
        for cap in doublequoted_string_key_regex.captures_iter(&new_json.clone()) {
            let cap_match = cap.name("key").unwrap().as_str();
            new_json = new_json.replacen(cap_match, &cap_match.replace("\n", ""), 1);
            new_json = new_json.replacen(cap_match, &cap_match.replace("\r", ""), 1);
            new_json =
                new_json.replacen(cap_match, &cap_match.replace("\t", "").replace("\t", ""), 1);
        }

        // For all double-quoted string keys with double-quoted values:
        let doublequoted_string_key_regex = Lazy::new(|| {
            Regex::new(
                &(r#"(?P<prevchar_key>[^"'][\s]*)"(?P<key>["#.to_string()
                    + SUPPORTED_KEY_CHARS_REGEX_STR
                    + r#"]*?[^"'])"(?P<val>\s*?:\s*?"[\s\S]*?")"#),
            )
            .unwrap()
        });
        for cap in doublequoted_string_key_regex.captures_iter(&new_json.clone()) {
            let cap_match = cap.name("key").unwrap().as_str();
            new_json = new_json.replacen(cap_match, &cap_match.replace("\n", ""), 1);
            new_json = new_json.replacen(cap_match, &cap_match.replace("\r", ""), 1);
            new_json =
                new_json.replacen(cap_match, &cap_match.replace("\t", "").replace("\t", ""), 1);
            new_json =
                new_json.replacen(cap_match, &cap_match.replace("\t", "").replace("\t", ""), 1);
        }

        // For all single-quoted object keys:
        let object_key_regex = Lazy::new(|| {
            Regex::new(
                &(r#"'(?P<key>["#.to_string()
                    + SUPPORTED_KEY_CHARS_REGEX_STR
                    + r#"]*?[^"'])'(?P<val>\s*?:\s*?[{\[])"#),
            )
            .unwrap()
        });
        for cap in object_key_regex.captures_iter(&new_json.clone()) {
            let cap_match = cap.name("key").unwrap().as_str();
            new_json = new_json.replacen(cap_match, &cap_match.replace("\n", ""), 1);
            new_json = new_json.replacen(cap_match, &cap_match.replace("\r", ""), 1);
            new_json =
                new_json.replacen(cap_match, &cap_match.replace("\t", "").replace("\t", ""), 1);
        }

        // For all double-quoted object keys:
        let object_key_regex = Lazy::new(|| {
            Regex::new(
                &(r#""(?P<key>["#.to_string()
                    + SUPPORTED_KEY_CHARS_REGEX_STR
                    + r#"]*?[^"'])"(?P<val>\s*?:\s*?[{\[])"#),
            )
            .unwrap()
        });
        for cap in object_key_regex.captures_iter(&new_json.clone()) {
            let cap_match = cap.name("key").unwrap().as_str();
            new_json = new_json.replacen(cap_match, &cap_match.replace("\n", ""), 1);
            new_json = new_json.replacen(cap_match, &cap_match.replace("\r", ""), 1);
            new_json =
                new_json.replacen(cap_match, &cap_match.replace("\t", "").replace("\t", ""), 1);
        }

        // For all single-quoted number keys:
        let number_key_regex = Lazy::new(|| {
            Regex::new(
                &(r#"(?P<before>[\[,{]\s*?)'(?P<key>["#.to_string()
                    + SUPPORTED_KEY_CHARS_REGEX_STR
                    + r#"]*?[^"'])'(?P<after>\s*?:\s*?[\d\-\.])"#),
            )
            .unwrap()
        });
        for cap in number_key_regex.captures_iter(&new_json.clone()) {
            let cap_match = cap.name("key").unwrap().as_str();
            new_json = new_json.replacen(cap_match, &cap_match.replace("\n", ""), 1);
            new_json = new_json.replacen(cap_match, &cap_match.replace("\r", ""), 1);
            new_json =
                new_json.replacen(cap_match, &cap_match.replace("\t", "").replace("\t", ""), 1);
        }

        // For all double-quoted number keys:
        let number_key_regex = Lazy::new(|| {
            Regex::new(
                &(r#"(?P<before>[\[,{]\s*?)"(?P<key>["#.to_string()
                    + SUPPORTED_KEY_CHARS_REGEX_STR
                    + r#"]*?[^"'])"(?P<after>\s*?:\s*?[\d\-\.])"#),
            )
            .unwrap()
        });
        for cap in number_key_regex.captures_iter(&new_json.clone()) {
            let cap_match = cap.name("key").unwrap().as_str();
            new_json = new_json.replacen(cap_match, &cap_match.replace("\n", ""), 1);
            new_json = new_json.replacen(cap_match, &cap_match.replace("\r", ""), 1);
            new_json =
                new_json.replacen(cap_match, &cap_match.replace("\t", "").replace("\t", ""), 1);
        }

        // For all single-quoted null and boolean keys:
        let null_boolean_key_regex = Lazy::new(|| {
            Regex::new(
                &(r#"(?P<before>[\[,{]\s*?)'(?P<key>["#.to_string()
                    + SUPPORTED_KEY_CHARS_REGEX_STR
                    + r#"]*?[^"'])'(?P<after>\s*?:\s*?(?:null|true|false))"#),
            )
            .unwrap()
        });
        for cap in null_boolean_key_regex.captures_iter(&new_json.clone()) {
            let cap_match = cap.name("key").unwrap().as_str();
            new_json = new_json.replacen(cap_match, &cap_match.replace("\n", ""), 1);
            new_json = new_json.replacen(cap_match, &cap_match.replace("\r", ""), 1);
            new_json =
                new_json.replacen(cap_match, &cap_match.replace("\t", "").replace("\t", ""), 1);
        }

        // For all double-quoted null and boolean keys:
        let null_boolean_key_regex = Lazy::new(|| {
            Regex::new(
                &(r#"(?P<before>[\[,{]\s*?)"(?P<key>["#.to_string()
                    + SUPPORTED_KEY_CHARS_REGEX_STR
                    + r#"]*?[^"'])"(?P<after>\s*?:\s*?(?:null|true|false))"#),
            )
            .unwrap()
        });
        for cap in null_boolean_key_regex.captures_iter(&new_json.clone()) {
            let cap_match = cap.name("key").unwrap().as_str();
            new_json = new_json.replacen(cap_match, &cap_match.replace("\n", ""), 1);
            new_json = new_json.replacen(cap_match, &cap_match.replace("\r", ""), 1);
            new_json =
                new_json.replacen(cap_match, &cap_match.replace("\t", "").replace("\t", ""), 1);
        }

        // For all single-quoted string values:
        let singlequoted_string_value_regex =
            Lazy::new(|| Regex::new(r#":[\s]*?'((?:[^'\\]|\\.)*)'"#).unwrap());
        for cap in singlequoted_string_value_regex.captures_iter(&new_json.clone()) {
            new_json = new_json.replacen(&cap[1], &cap[1].replace("\r", "\\r"), 1);
            new_json = new_json.replacen(&cap[1], &cap[1].replace("\n", "\\n"), 1);
            new_json = new_json.replacen(&cap[1], &cap[1].replace("\t", "\\t"), 1);
        }

        // For all double-quoted string values:
        let doublequoted_string_value_regex =
            Lazy::new(|| Regex::new(r#":[\s]*?"((?:[^"\\]|\\.)*)""#).unwrap());
        for cap in doublequoted_string_value_regex.captures_iter(&new_json.clone()) {
            new_json = new_json.replacen(&cap[1], &cap[1].replace("\r", "\\r"), 1);
            new_json = new_json.replacen(&cap[1], &cap[1].replace("\n", "\\n"), 1);
            new_json = new_json.replacen(&cap[1], &cap[1].replace("\t", "\\t"), 1);
        }
    }

    new_json
}

/// Unescape ctrl-characters from the JSON string values
/// and remove ctrl-characters from the JSON keys without keyquotes.
///
/// This method will unescape `newlines`, `tabs` and `carriage returns` in the JSON string values
/// and remove `newlines`, `tabs` and `carriage returns` in the JSON keys without keyquotes.
///
/// # Arguments
///
/// * `json` - The JSON string.
///
/// # Examples
///
/// ```
/// use json_keyquotes_convert::{json_key_quote_utils};
///
/// let json_unescaped = json_key_quote_utils::json_unescape_ctrlchars(r#"{key: "va\nl"}"#);
/// assert_eq!(json_unescaped, r#"{key: "va
/// l"}"#);
///
/// let json_already_unescaped = json_key_quote_utils::json_unescape_ctrlchars(&json_unescaped);
/// assert_eq!(json_already_unescaped, r#"{key: "va
/// l"}"#);
/// ```
pub fn json_unescape_ctrlchars(json: &str) -> String {
    // Replace all escaped control characters with their unescaped variants:

    let mut new_json = json.to_owned();

    // Two iterations are needed for the tab unescaping:

    for _n in 0..2 {
        // For all single-quoted string keys:
        let singlequoted_string_key_regex = Lazy::new(|| {
            Regex::new(
                &(r#"(?P<prevchar_key>[^"'][\s]*)(?P<key>["#.to_string()
                    + SUPPORTED_KEY_CHARS_REGEX_STR
                    + r#"]*?[^"'])(?P<val>\s*?:\s*?'[\s\S]*?')"#),
            )
            .unwrap()
        });
        for cap in singlequoted_string_key_regex.captures_iter(&new_json.clone()) {
            let cap_match = cap.name("key").unwrap().as_str();
            new_json = new_json.replacen(cap_match, &cap_match.replace("\\r", ""), 1);
            new_json = new_json.replacen(cap_match, &cap_match.replace("\\n", ""), 1);
            new_json = new_json.replacen(cap_match, &cap_match.replace("\\t", ""), 1);
        }

        // For all double-quoted string keys:
        let doublequoted_string_key_regex = Lazy::new(|| {
            Regex::new(
                &(r#"(?P<prevchar_key>[^"'][\s]*)(?P<key>["#.to_string()
                    + SUPPORTED_KEY_CHARS_REGEX_STR
                    + r#"]*?[^"'])(?P<val>\s*?:\s*?"[\s\S]*?")"#),
            )
            .unwrap()
        });
        for cap in doublequoted_string_key_regex.captures_iter(&new_json.clone()) {
            let cap_match = cap.name("key").unwrap().as_str();
            new_json = new_json.replacen(cap_match, &cap_match.replace("\\r", ""), 1);
            new_json = new_json.replacen(cap_match, &cap_match.replace("\\n", ""), 1);
            new_json = new_json.replacen(cap_match, &cap_match.replace("\\t", ""), 1);
        }

        // For all object keys:
        let object_key_regex = Lazy::new(|| {
            Regex::new(
                &(r#"(?P<key>["#.to_string()
                    + SUPPORTED_KEY_CHARS_REGEX_STR
                    + r#"]*?[^"'])(?P<val>\s*?:\s*?[{\[])"#),
            )
            .unwrap()
        });
        for cap in object_key_regex.captures_iter(&new_json.clone()) {
            let cap_match = cap.name("key").unwrap().as_str();
            new_json = new_json.replacen(cap_match, &cap_match.replace("\\r", ""), 1);
            new_json = new_json.replacen(cap_match, &cap_match.replace("\\n", ""), 1);
            new_json = new_json.replacen(cap_match, &cap_match.replace("\\t", ""), 1);
        }

        // For all number keys:
        let number_key_regex = Lazy::new(|| {
            Regex::new(
                &(r#"(?P<before>[\[,{]\s*?)(?P<key>["#.to_string()
                    + SUPPORTED_KEY_CHARS_REGEX_STR
                    + r#"]*?[^"'])(?P<after>\s*?:\s*?[\d\-\.])"#),
            )
            .unwrap()
        });
        for cap in number_key_regex.captures_iter(&new_json.clone()) {
            let cap_match = cap.name("key").unwrap().as_str();
            new_json = new_json.replacen(cap_match, &cap_match.replace("\\r", ""), 1);
            new_json = new_json.replacen(cap_match, &cap_match.replace("\\n", ""), 1);
            new_json = new_json.replacen(cap_match, &cap_match.replace("\\t", ""), 1);
        }

        // For all null and boolean keys:
        let null_boolean_key_regex = Lazy::new(|| {
            Regex::new(
                &(r#"(?P<before>[\[,{]\s*?)(?P<key>["#.to_string()
                    + SUPPORTED_KEY_CHARS_REGEX_STR
                    + r#"]*?[^"'])(?P<after>\s*?:\s*?(?:null|true|false))"#),
            )
            .unwrap()
        });
        for cap in null_boolean_key_regex.captures_iter(&new_json.clone()) {
            let cap_match = cap.name("key").unwrap().as_str();
            new_json = new_json.replacen(cap_match, &cap_match.replace("\\r", ""), 1);
            new_json = new_json.replacen(cap_match, &cap_match.replace("\\n", ""), 1);
            new_json = new_json.replacen(cap_match, &cap_match.replace("\\t", ""), 1);
        }

        // For all single-quoted string values:
        let singlequoted_string_value_regex =
            Lazy::new(|| Regex::new(r#":[\s]*?'((?:[^'\\]|\\.)*)'"#).unwrap());
        for cap in singlequoted_string_value_regex.captures_iter(&new_json.clone()) {
            new_json = new_json.replacen(&cap[1], &cap[1].replace("\\r", "\r"), 1);
            new_json = new_json.replacen(&cap[1], &cap[1].replace("\\n", "\n"), 1);
            new_json = new_json.replacen(&cap[1], &cap[1].replace("\\t", "\t"), 1);
        }

        // For all double-quoted string values:
        let doublequoted_string_value_regex =
            Lazy::new(|| Regex::new(r#":[\s]*?"((?:[^"\\]|\\.)*)""#).unwrap());
        for cap in doublequoted_string_value_regex.captures_iter(&new_json.clone()) {
            new_json = new_json.replacen(&cap[1], &cap[1].replace("\\r", "\r"), 1);
            new_json = new_json.replacen(&cap[1], &cap[1].replace("\\n", "\n"), 1);
            new_json = new_json.replacen(&cap[1], &cap[1].replace("\\t", "\t"), 1);
        }
    }

    new_json
}

#[cfg(test)]
mod tests {
    use crate::{json_key_quote_utils, load_write_utils, Quotes};
    use std::path::Path;

    const SUPPORTED_KEY_CHARS: &str = r#"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#$%€^&*()-_=+\|;"'.<>/?"#;
    const SUPPORTED_VALUE_CHARS: &str = r#"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#$%€^&*()-_=+\|:;"'.<>/?"#;

    #[test]
    fn test_json_convert_without_to_with_keyquotes() {
        let path = Path::new("./tmp_without_keyquotes");
        std::fs::copy(
            "./test_resources/Test_without_keyquotes.json",
            "./tmp_without_keyquotes",
        )
        .unwrap();
        json_key_quote_utils::json_convert_without_to_with_keyquotes(
            path,
            crate::Quotes::DoubleQuote,
        );
        let converted_file_contents = load_write_utils::load_json(path).unwrap();
        let expected_file_contents =
            load_write_utils::load_json(Path::new("./test_resources/Test_with_keyquotes.json"))
                .unwrap();
        assert!(converted_file_contents == expected_file_contents);
        std::fs::remove_file("./tmp_without_keyquotes").unwrap();
    }

    #[test]
    fn test_json_convert_with_to_without_keyquotes() {
        let path = Path::new("./tmp_with_keyquotes");
        std::fs::copy(
            "./test_resources/Test_with_keyquotes.json",
            "./tmp_with_keyquotes",
        )
        .unwrap();
        json_key_quote_utils::json_convert_with_to_without_keyquotes(path);
        let converted_file_contents = load_write_utils::load_json(path).unwrap();
        let expected_file_contents =
            load_write_utils::load_json(Path::new("./test_resources/Test_without_keyquotes.json"))
                .unwrap();
        assert!(converted_file_contents == expected_file_contents);
        std::fs::remove_file("./tmp_with_keyquotes").unwrap();
    }

    #[test]
    fn test_json_add_key_quotes_single_quote_add_supported_characters() {
        let supported_key_chars = SUPPORTED_KEY_CHARS.replacen(r#"'"#, r#"\'"#, 1);
        let supported_value_chars = SUPPORTED_VALUE_CHARS.replacen(r#"'"#, r#"\'"#, 1);

        let json =
            r#"{"#.to_string() + &supported_key_chars + r#": '"# + &supported_value_chars + r#"'}"#;
        let expected = r#"{'"#.to_string()
            + &supported_key_chars
            + r#"': '"#
            + &supported_value_chars
            + r#"'}"#;

        let actual = json_key_quote_utils::json_add_key_quotes(&json, Quotes::SingleQuote);
        let actual_second_pass =
            json_key_quote_utils::json_add_key_quotes(&actual, Quotes::SingleQuote);

        assert_eq!(expected, actual);
        assert_eq!(expected, actual_second_pass);
    }

    #[test]
    fn test_json_add_key_quotes_double_quote_add_supported_characters() {
        let supported_key_chars = SUPPORTED_KEY_CHARS.replacen(r#"""#, r#"\""#, 1);
        let supported_value_chars = SUPPORTED_VALUE_CHARS.replacen(r#"""#, r#"\""#, 1);

        let json =
            r#"{"#.to_string() + &supported_key_chars + r#": ""# + &supported_value_chars + r#""}"#;
        let expected = r#"{""#.to_string()
            + &supported_key_chars
            + r#"": ""#
            + &supported_value_chars
            + r#""}"#;

        let actual = json_key_quote_utils::json_add_key_quotes(&json, Quotes::DoubleQuote);
        let actual_second_pass =
            json_key_quote_utils::json_add_key_quotes(&actual, Quotes::DoubleQuote);

        assert_eq!(expected, actual);
        assert_eq!(expected, actual_second_pass);
    }

    #[test]
    fn test_json_remove_key_quotes_single_quoted_supported_characters() {
        let supported_key_chars = SUPPORTED_KEY_CHARS.replacen(r#"'"#, r#"\'"#, 1);
        let supported_value_chars = SUPPORTED_VALUE_CHARS.replacen(r#"'"#, r#"\'"#, 1);

        let json = r#"{'"#.to_string()
            + &supported_key_chars
            + r#"': ""#
            + &supported_value_chars
            + r#""}"#;
        let expected =
            r#"{"#.to_string() + &supported_key_chars + r#": ""# + &supported_value_chars + r#""}"#;

        let actual = json_key_quote_utils::json_remove_key_quotes(&json);
        let actual_second_pass = json_key_quote_utils::json_remove_key_quotes(&actual);

        assert_eq!(expected, actual);
        assert_eq!(expected, actual_second_pass);
    }

    #[test]
    fn test_json_remove_key_quotes_double_quoted_supported_characters() {
        let supported_key_chars = SUPPORTED_KEY_CHARS.replacen(r#"""#, r#"\""#, 1);
        let supported_value_chars = SUPPORTED_VALUE_CHARS.replacen(r#"""#, r#"\""#, 1);

        let json = r#"{""#.to_string()
            + &supported_key_chars
            + r#"": ""#
            + &supported_value_chars
            + r#""}"#;
        let expected =
            r#"{"#.to_string() + &supported_key_chars + r#": ""# + &supported_value_chars + r#""}"#;

        let actual = json_key_quote_utils::json_remove_key_quotes(&json);
        let actual_second_pass = json_key_quote_utils::json_remove_key_quotes(&actual);

        assert_eq!(expected, actual);
        assert_eq!(expected, actual_second_pass);
    }

    #[test]
    fn test_json_escape_ctrlchars_single_quoted_supported_characters() {
        let supported_key_chars = SUPPORTED_KEY_CHARS.replacen(r#"'"#, r#"\'"#, 1);
        let supported_value_chars = SUPPORTED_VALUE_CHARS.replacen(r#"'"#, r#"\'"#, 1);

        let key = supported_key_chars.to_string();
        let value = supported_value_chars
            .replacen(
                "A", r#"A
"#, 1,
            )
            .replacen("B", r#"B	"#, 1);

        let expected_key = supported_key_chars.to_string();
        let expected_value = supported_value_chars
            .replacen("A", r#"A\n"#, 1)
            .replacen("B", r#"B\t"#, 1);

        let json = r#"{'"#.to_string() + &key + r#"': '"# + &value + r#"'}"#;
        let expected = r#"{'"#.to_string() + &expected_key + r#"': '"# + &expected_value + r#"'}"#;

        let actual = json_key_quote_utils::json_escape_ctrlchars(&json);
        let actual_second_pass = json_key_quote_utils::json_escape_ctrlchars(&actual);

        assert_eq!(expected, actual);
        assert_eq!(expected, actual_second_pass);
    }

    #[test]
    fn test_json_escape_ctrlchars_double_quoted_supported_characters() {
        let supported_key_chars = SUPPORTED_KEY_CHARS.replacen(r#"""#, r#"\""#, 1);
        let supported_value_chars = SUPPORTED_VALUE_CHARS.replacen(r#"""#, r#"\""#, 1);

        let key = supported_key_chars.to_string();
        let value = supported_value_chars
            .replacen(
                "A", r#"A
"#, 1,
            )
            .replacen("B", r#"B	"#, 1);

        let expected_key = supported_key_chars.to_string();
        let expected_value = supported_value_chars
            .replacen("A", r#"A\n"#, 1)
            .replacen("B", r#"B\t"#, 1);

        let json = r#"{""#.to_string() + &key + r#"": ""# + &value + r#""}"#;
        let expected = r#"{""#.to_string() + &expected_key + r#"": ""# + &expected_value + r#""}"#;

        let actual = json_key_quote_utils::json_escape_ctrlchars(&json);
        let actual_second_pass = json_key_quote_utils::json_escape_ctrlchars(&actual);

        assert_eq!(expected, actual);
        assert_eq!(expected, actual_second_pass);
    }

    #[test]
    fn test_json_escape_ctrlchars_unquoted_keys_supported_characters() {
        let supported_value_chars = SUPPORTED_VALUE_CHARS.replacen(r#"""#, r#"\""#, 1);

        let key = SUPPORTED_KEY_CHARS
            .replacen(
                "A", r#"A
"#, 1,
            )
            .replacen("B", r#"B	"#, 1);
        let value = supported_value_chars
            .replacen(
                "A", r#"A
"#, 1,
            )
            .replacen("B", r#"B	"#, 1);

        let expected_value = supported_value_chars
            .replacen("A", r#"A\n"#, 1)
            .replacen("B", r#"B\t"#, 1);

        let json = r#"{"#.to_string() + &key + r#": ""# + &value + r#""}"#;
        let expected = r#"{"#.to_string() + &key + r#": ""# + &expected_value + r#""}"#;

        let actual = json_key_quote_utils::json_escape_ctrlchars(&json);
        let actual_second_pass = json_key_quote_utils::json_escape_ctrlchars(&actual);

        assert_eq!(expected, actual);
        assert_eq!(expected, actual_second_pass);
    }

    #[test]
    fn test_json_unescape_ctrlchars_single_quoted_supported_characters() {
        let supported_key_chars = SUPPORTED_KEY_CHARS.replacen(r#"'"#, r#"\'"#, 1);
        let supported_value_chars = SUPPORTED_VALUE_CHARS.replacen(r#"'"#, r#"\'"#, 1);

        let key = supported_key_chars.to_string();
        let value = supported_value_chars
            .replacen("A", r#"A\n"#, 1)
            .replacen("B", r#"B\t"#, 1);

        let expected_key = supported_key_chars.to_string();
        let expected_value = supported_value_chars
            .replacen(
                "A", r#"A
"#, 1,
            )
            .replacen("B", r#"B	"#, 1);

        let json = r#"{"#.to_string() + &key + r#": '"# + &value + r#"'}"#;
        let expected = r#"{"#.to_string() + &expected_key + r#": '"# + &expected_value + r#"'}"#;

        let actual = json_key_quote_utils::json_unescape_ctrlchars(&json);
        let actual_second_pass = json_key_quote_utils::json_unescape_ctrlchars(&actual);

        assert_eq!(expected, actual);
        assert_eq!(expected, actual_second_pass);
    }

    #[test]
    fn test_json_unescape_ctrlchars_double_quoted_supported_characters() {
        let supported_key_chars = SUPPORTED_KEY_CHARS.replacen(r#"""#, r#"\""#, 1);
        let supported_value_chars = SUPPORTED_VALUE_CHARS.replacen(r#"""#, r#"\""#, 1);

        let key = supported_key_chars.to_string();
        let value = supported_value_chars
            .replacen("A", r#"A\n"#, 1)
            .replacen("B", r#"B\t"#, 1);

        let expected_key = supported_key_chars.to_string();
        let expected_value = supported_value_chars
            .replacen(
                "A", r#"A
"#, 1,
            )
            .replacen("B", r#"B	"#, 1);

        let json = r#"{"#.to_string() + &key + r#": ""# + &value + r#""}"#;
        let expected = r#"{"#.to_string() + &expected_key + r#": ""# + &expected_value + r#""}"#;

        let actual = json_key_quote_utils::json_unescape_ctrlchars(&json);
        let actual_second_pass = json_key_quote_utils::json_unescape_ctrlchars(&actual);

        assert_eq!(expected, actual);
        assert_eq!(expected, actual_second_pass);
    }

    #[test]
    fn test_json_unescape_ctrlchars_double_quoted_keys_supported_characters() {
        let supported_value_chars = SUPPORTED_VALUE_CHARS.replacen(r#"""#, r#"\""#, 1);

        let key = SUPPORTED_KEY_CHARS
            .replacen("A", r#"A\n"#, 1)
            .replacen("B", r#"B\t"#, 1);
        let value = supported_value_chars
            .replacen("A", r#"A\n"#, 1)
            .replacen("B", r#"B\t"#, 1);

        let expected_value = supported_value_chars
            .replacen(
                "A", r#"A
"#, 1,
            )
            .replacen("B", r#"B	"#, 1);

        let json = r#"{""#.to_string() + &key + r#"": ""# + &value + r#""}"#;
        let expected = r#"{""#.to_string() + &key + r#"": ""# + &expected_value + r#""}"#;

        let actual = json_key_quote_utils::json_unescape_ctrlchars(&json);
        let actual_second_pass = json_key_quote_utils::json_unescape_ctrlchars(&actual);

        assert_eq!(expected, actual);
        assert_eq!(expected, actual_second_pass);
    }
}