Reduce code duplication in to json command (#4551)

This commit is contained in:
Joseph T. Lyons 2022-02-19 15:46:20 -05:00 committed by GitHub
parent ac99ac003a
commit efd62f917f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -30,10 +30,27 @@ impl Command for ToJson {
input: PipelineData,
) -> Result<nu_protocol::PipelineData, ShellError> {
let raw = call.has_flag("raw");
if raw {
to_json_raw(call, input)
let json_function = if raw {
nu_json::to_string_raw
} else {
to_json(call, input)
nu_json::to_string
};
let span = call.head;
let value = input.into_value(span);
let json_value = value_to_json_value(&value)?;
match json_function(&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()),
}
}
@ -94,44 +111,6 @@ fn json_list(input: &[Value]) -> Result<Vec<nu_json::Value>, ShellError> {
Ok(out)
}
fn to_json(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(&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()),
}
}
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::*;