Skip to content

Commit

Permalink
Merge pull request #1723 from biryukovmaxim/feature/better_json_commo…
Browse files Browse the repository at this point in the history
…n_table_output

improve json output for CommandOutput::Table
  • Loading branch information
etam authored Mar 30, 2022
2 parents 8621fb0 + d121b72 commit eb31aad
Showing 1 changed file with 35 additions and 8 deletions.
43 changes: 35 additions & 8 deletions core/serv-api/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use anyhow::Result;
use prettytable::{color, format, format::TableFormat, Attr, Cell, Row, Table};
use serde::Serialize;
use std::collections::HashMap;
use std::path::PathBuf;

#[derive(Clone, Debug, Default)]
Expand Down Expand Up @@ -55,14 +56,40 @@ impl CommandOutput {
header,
} => {
if json_output {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"headers": columns,
"values": values
}))
.unwrap()
)
let columns_size_eq_values_size = values.iter().all(|row| match row {
serde_json::Value::Array(values) => values.len() == columns.len(),
_ => false,
});
if columns_size_eq_values_size {
let kvs: Vec<HashMap<&String, &serde_json::Value>> = values
.iter()
.map(|row| match row {
serde_json::Value::Array(row_values)
if columns.len() == row_values.len() =>
{
columns
.into_iter()
.enumerate()
.map(|(idx, key)| (key, &row_values[idx]))
.collect()
}
_ => unreachable!(),
})
.collect();
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!(kvs)).unwrap()
)
} else {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"headers": columns,
"values": values
}))
.unwrap()
)
}
} else {
if let Some(txt) = header {
println!("{}", txt);
Expand Down

0 comments on commit eb31aad

Please sign in to comment.