add in a raw flag in the command to json (#555)

* add in the method to_string_raw

* add in a raw flag to json

* add in a test
This commit is contained in:
Michael Angerman
2021-12-22 11:56:49 -08:00
committed by GitHub
parent 061c822c5d
commit 5d3b63fa90
4 changed files with 50 additions and 3 deletions

View File

@ -13,7 +13,9 @@ impl Command for ToJson {
}
fn signature(&self) -> Signature {
Signature::build("to json").category(Category::Formats)
Signature::build("to json")
.switch("raw", "remove all of the whitespace", Some('r'))
.category(Category::Formats)
}
fn usage(&self) -> &str {
@ -27,7 +29,12 @@ impl Command for ToJson {
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, ShellError> {
to_json(call, input)
let raw = call.has_flag("raw");
if raw {
to_json_raw(call, input)
} else {
to_json(call, input)
}
}
fn examples(&self) -> Vec<Example> {
@ -106,6 +113,25 @@ fn to_json(call: &Call, input: PipelineData) -> Result<PipelineData, ShellError>
}
}
fn to_json_raw(call: &Call, input: PipelineData) -> Result<PipelineData, ShellError> {
let span = call.head;
let value = input.into_value(span);
let json_value = value_to_json_value(&value)?;
match nu_json::to_string_raw(&json_value) {
Ok(serde_json_string) => Ok(Value::String {
val: serde_json_string,
span,
}
.into_pipeline_data()),
_ => Ok(Value::Error {
error: ShellError::CantConvert("JSON".into(), value.get_type().to_string(), span),
}
.into_pipeline_data()),
}
}
#[cfg(test)]
mod test {
use super::*;