Add ability to choose between minified and pretty-printed JSON (#4161)

This commit is contained in:
Ilia 2024-05-29 14:06:27 +03:00 committed by GitHub
parent b73b3ca335
commit 6d07f702e1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 17 additions and 5 deletions

View File

@ -153,6 +153,10 @@ pub struct QueryCommand {
/// The format to serialize in
#[clap(long = "format", default_value = "json")]
pub format: SerializationFormat,
/// Whether to pretty-print the serialized output
#[clap(long)]
pub pretty: bool,
}
// Output file format for query command

View File

@ -99,20 +99,28 @@ fn format(elements: Vec<Content>, command: &QueryCommand) -> StrResult<String> {
let Some(value) = mapped.first() else {
bail!("no such field found for element");
};
serialize(value, command.format)
serialize(value, command.format, command.pretty)
} else {
serialize(&mapped, command.format)
serialize(&mapped, command.format, command.pretty)
}
}
/// Serialize data to the output format.
fn serialize(data: &impl Serialize, format: SerializationFormat) -> StrResult<String> {
fn serialize(
data: &impl Serialize,
format: SerializationFormat,
pretty: bool,
) -> StrResult<String> {
match format {
SerializationFormat::Json => {
serde_json::to_string_pretty(data).map_err(|e| eco_format!("{e}"))
if pretty {
serde_json::to_string_pretty(data).map_err(|e| eco_format!("{e}"))
} else {
serde_json::to_string(data).map_err(|e| eco_format!("{e}"))
}
}
SerializationFormat::Yaml => {
serde_yaml::to_string(&data).map_err(|e| eco_format!("{e}"))
serde_yaml::to_string(data).map_err(|e| eco_format!("{e}"))
}
}
}