Skip to content

Commit

Permalink
Merge pull request #361 from zuisong/serde_json_formatter
Browse files Browse the repository at this point in the history
use serde_json format full json
  • Loading branch information
ducaale committed Apr 12, 2024
2 parents 269941e + 0957fa3 commit 4fd1d9d
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 6 deletions.
10 changes: 10 additions & 0 deletions src/formatting.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::io::{self, Write};

use serde::Serialize;
use syntect::dumps::from_binary;
use syntect::easy::HighlightLines;
use syntect::highlighting::ThemeSet;
Expand All @@ -17,6 +18,15 @@ pub fn get_json_formatter(indent_level: usize) -> jsonxf::Formatter {
fmt
}

pub fn serde_json_format(indent_level: usize, text: &str, write: impl Write) -> io::Result<()> {
let indent = " ".repeat(indent_level);
let formatter = serde_json::ser::PrettyFormatter::with_indent(indent.as_bytes());
let value = serde_json::from_str::<serde_json::Value>(text)?;
let mut serializer = serde_json::Serializer::with_formatter(write, formatter);
value.serialize(&mut serializer)?;
Ok(())
}

static TS: once_cell::sync::Lazy<ThemeSet> = once_cell::sync::Lazy::new(|| {
from_binary(include_bytes!(concat!(
env!("OUT_DIR"),
Expand Down
17 changes: 11 additions & 6 deletions src/printer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ use reqwest::header::{
use reqwest::Version;
use url::Url;

use crate::cli::FormatOptions;
use crate::decoder::{decompress, get_compression_type};
use crate::{
buffer::Buffer,
cli::FormatOptions,
cli::{Pretty, Theme},
decoder::{decompress, get_compression_type},
formatting::serde_json_format,
formatting::{get_json_formatter, Highlighter},
middleware::ResponseExt,
utils::{copy_largebuf, test_mode, BUFFER_SIZE},
Expand Down Expand Up @@ -166,16 +167,19 @@ impl Printer {
return self.print_syntax_text(text, "json");
}

let mut formatter = get_json_formatter(self.json_indent_level);
if self.color {
let mut buf = Vec::new();
formatter.format_buf(text.as_bytes(), &mut buf)?;
serde_json_format(self.json_indent_level, text, &mut buf)?;
buf.write_all(&[b'\n', b'\n'])?;
// in principle, buf should already be valid UTF-8,
// because JSONXF doesn't mangle it
let text = String::from_utf8_lossy(&buf);
self.print_colorized_text(&text, "json")
} else {
formatter.format_buf(text.as_bytes(), &mut self.buffer)
serde_json_format(self.json_indent_level, text, &mut self.buffer)?;
self.buffer.write_all(&[b'\n', b'\n'])?;
self.buffer.flush()?;
Ok(())
}
}

Expand Down Expand Up @@ -749,10 +753,11 @@ fn get_charset(response: &Response) -> Option<&'static Encoding> {
mod tests {
use indoc::indoc;

use super::*;
use crate::utils::random_string;
use crate::{buffer::Buffer, cli::Cli, vec_of_strings};

use super::*;

fn run_cmd(args: impl IntoIterator<Item = String>, is_stdout_tty: bool) -> Printer {
let args = Cli::try_parse_from(args).unwrap();
let theme = args.style.unwrap_or_default();
Expand Down
38 changes: 38 additions & 0 deletions tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,44 @@ fn basic_json_post() {
}
"#});
}
#[test]
fn full_json_response_utf8_decode() {
let server = server::http(|_| async move {
hyper::Response::builder()
.header(hyper::header::CONTENT_TYPE, "application/json")
.body(r#"{"hello": "\u4f60\u597d"}"#.into())
.unwrap()
});

get_command()
.arg("--print=b")
.arg("-S")
.arg("--pretty=format")
.arg("post")
.arg(server.base_url())
.assert()
.stdout(indoc! {r#"
{
"hello": "\u4f60\u597d"
}
"#});

get_command()
.arg("--print=b")
.arg("--pretty=format")
.arg("post")
.arg(server.base_url())
.assert()
.stdout(indoc! {r#"
{
"hello": "你好"
}
"#});
}

Expand Down

0 comments on commit 4fd1d9d

Please sign in to comment.