mod chars;
mod error;
mod parser;
#[cfg(feature = "serde")]
pub use error::JsonRepairParseError;
pub use error::{JsonRepairError, JsonRepairErrorKind};
#[derive(Debug)]
#[non_exhaustive]
pub enum JsonRepairWriteError {
Repair(JsonRepairError),
Write(std::io::Error),
}
impl std::fmt::Display for JsonRepairWriteError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Repair(err) => err.fmt(f),
Self::Write(err) => write!(f, "failed to write repaired JSON: {err}"),
}
}
}
impl std::error::Error for JsonRepairWriteError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Repair(err) => Some(err),
Self::Write(err) => Some(err),
}
}
}
impl From<JsonRepairError> for JsonRepairWriteError {
fn from(err: JsonRepairError) -> Self {
Self::Repair(err)
}
}
impl From<std::io::Error> for JsonRepairWriteError {
fn from(err: std::io::Error) -> Self {
Self::Write(err)
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum JsonRepairStreamError {
Read(std::io::Error),
Repair(JsonRepairError),
Write(std::io::Error),
}
impl std::fmt::Display for JsonRepairStreamError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Read(err) => write!(f, "failed to read JSON input: {err}"),
Self::Repair(err) => err.fmt(f),
Self::Write(err) => write!(f, "failed to write repaired JSON: {err}"),
}
}
}
impl std::error::Error for JsonRepairStreamError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Read(err) => Some(err),
Self::Repair(err) => Some(err),
Self::Write(err) => Some(err),
}
}
}
pub fn jsonrepair_to_writer<W>(input: &str, writer: &mut W) -> Result<(), JsonRepairWriteError>
where
W: std::io::Write + ?Sized,
{
let repaired = jsonrepair(input)?;
writer.write_all(repaired.as_bytes())?;
Ok(())
}
pub fn jsonrepair_reader_to_writer<R, W>(
mut reader: R,
writer: &mut W,
) -> Result<(), JsonRepairStreamError>
where
R: std::io::Read,
W: std::io::Write + ?Sized,
{
let mut input = String::new();
reader
.read_to_string(&mut input)
.map_err(JsonRepairStreamError::Read)?;
let repaired = jsonrepair(&input).map_err(JsonRepairStreamError::Repair)?;
writer
.write_all(repaired.as_bytes())
.map_err(JsonRepairStreamError::Write)?;
Ok(())
}
pub fn jsonrepair(input: &str) -> Result<String, JsonRepairError> {
let repairer = parser::JsonRepairer::new(input);
repairer.repair()
}
#[cfg(feature = "serde")]
pub fn jsonrepair_value(input: &str) -> Result<serde_json::Value, JsonRepairParseError> {
jsonrepair_parse(input)
}
#[cfg(feature = "serde")]
pub fn jsonrepair_parse<T>(input: &str) -> Result<T, JsonRepairParseError>
where
T: serde::de::DeserializeOwned,
{
let repaired = jsonrepair(input)?;
serde_json::from_str(&repaired).map_err(JsonRepairParseError::from)
}