Skip to content

Provide a way to stylize/colorize JsonWriter output #105

Description

@tliron

Problem solved by the enhancement

It is currently impossible to achieve ANSI colorization via the existing JsonWriter implementation.

Enhancement description

The issue is that the private should_escape function will escape ANSI codes and there does not seem to be a way to get around this.

A straightforward solution might be to add a flag to WriterSettings to not escape ANSI codes. However, I am not sure this is the best solution, because ANSI codes might be present in the actual data, and strictly speaking those should be escaped.

Instead, I would suggest adding a write_unescaped method to JsonWriter. This would allow users to wrap JsonStreamWriter and provide their own ANSI code output before/after writing the actual properly escaped content, e.g.:

impl JsonWriter for MyJsonWriter {
    ...
    // self.writer is a wrapped JsonStreamWriter
    fn string_value(&mut self, value: &str) -> Result<(), io::Error> {
        self.writer.write_unescaped("[some ansi codes"])?;
        self.writer.string_value(value)?;
        self.writer.write_unescaped("[some ansi codes"])
    }
}

Alternatives / workarounds

Writing is ostensibly handled by the JsonStringWriter trait. However, JsonStreamWriter does not provide a way to replace this implementation. There is an internal StringValueWriterImpl that calls a private write_string_value_piece, and no access to the underlying writer, which is owned by JsonStreamWriter.

A workaround would be writing an entire custom JsonWriter implementation.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions