diff --git a/crates/nu-json/src/ser.rs b/crates/nu-json/src/ser.rs index b29a988295..4826c34c4f 100644 --- a/crates/nu-json/src/ser.rs +++ b/crates/nu-json/src/ser.rs @@ -4,6 +4,7 @@ use std::fmt::{Display, LowerExp}; use std::io; +use std::io::{BufRead, BufReader}; use std::num::FpCategory; use super::error::{Error, ErrorCode, Result}; @@ -1032,7 +1033,20 @@ where T: ser::Serialize, { let vec = to_vec(value)?; - let mut string = String::from_utf8(vec)?; - string.retain(|c| !c.is_whitespace()); + let string = remove_json_whitespace(vec); Ok(string) } + +fn remove_json_whitespace(v: Vec) -> String { + let reader = BufReader::new(&v[..]); + let mut output = String::new(); + for line in reader.lines() { + match line { + Ok(line) => output.push_str(line.trim().trim_end()), + _ => { + eprintln!("Error removing JSON whitespace"); + } + } + } + output +} diff --git a/src/tests/test_converters.rs b/src/tests/test_converters.rs index d4b935c730..16fda1c3d2 100644 --- a/src/tests/test_converters.rs +++ b/src/tests/test_converters.rs @@ -15,9 +15,25 @@ fn from_json_2() -> TestResult { } #[test] -fn to_json_raw_flag() -> TestResult { +fn to_json_raw_flag_1() -> TestResult { run_test( "[[a b]; [jim susie] [3 4]] | to json -r", - r#"[{"a":"jim","b":"susie"},{"a":3,"b":4}]"#, + r#"[{"a": "jim","b": "susie"},{"a": 3,"b": 4}]"#, + ) +} + +#[test] +fn to_json_raw_flag_2() -> TestResult { + run_test( + "[[\"a b\" c]; [jim susie] [3 4]] | to json -r", + r#"[{"a b": "jim","c": "susie"},{"a b": 3,"c": 4}]"#, + ) +} + +#[test] +fn to_json_raw_flag_3() -> TestResult { + run_test( + "[[\"a b\" \"c d\"]; [\"jim smith\" \"susie roberts\"] [3 4]] | to json -r", + r#"[{"a b": "jim smith","c d": "susie roberts"},{"a b": 3,"c d": 4}]"#, ) }