1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
//! Read and Write in JSON format.
//!
//! ### Configuration
//!
//! | key | alias | Description | Default Value | Possible Values |
//! | ---------- | ----- | ---------------------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------ |
//! | type | - | Required in order to use this document. | `json` | `json` |
//! | metadata | meta | Metadata describe the resource. | `null` | [`crate::Metadata`] |
//! | is_pretty | - | Display json data readable for human. | `false` | `false` / `true` |
//! | entry_path | - | Use this field if you want target a specific field in the json object. | `null` | String in [json pointer format](https://datatracker.ietf.org/doc/html/rfc6901) |
//!
//! Examples:
//!
//! ```json
//! [
//! {
//! "type": "read",
//! "document": {
//! "type": "json",
//! "entry_path": "/0"
//! }
//! },
//! {
//! "type": "write",
//! "document": {
//! "type": "json",
//! "is_pretty": true
//! }
//! }
//! ]
//! ```
//!
//! input:
//!
//! ```json
//! [
//! {"field1":"value1"},
//! {"field1":"value2"},
//! ...
//! ]
//! ```
//!
//! output:
//!
//! ```json
//! [
//! {
//! "field1":"value1"
//! }
//! ]
//! ```
use crate::document::Document;
use crate::DataResult;
use crate::DataSet;
use crate::Metadata;
use json_value_search::Search;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::io;
const DEFAULT_TERMINATOR: &str = ",";
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct Json {
#[serde(rename = "metadata")]
#[serde(alias = "meta")]
pub metadata: Metadata,
pub is_pretty: bool,
pub entry_path: Option<String>,
}
impl Default for Json {
fn default() -> Self {
let metadata = Metadata {
terminator: Some(DEFAULT_TERMINATOR.to_string()),
mime_type: Some(mime::APPLICATION.to_string()),
mime_subtype: Some(mime::JSON.to_string()),
charset: Some(mime::UTF_8.to_string()),
..Default::default()
};
Json {
metadata,
is_pretty: false,
entry_path: None,
}
}
}
impl Document for Json {
/// See [`Document::metadata`] for more details.
fn metadata(&self) -> Metadata {
Json::default().metadata.merge(&self.metadata)
}
/// See [`Document::set_entry_path`] for more details.
fn set_entry_path(&mut self, entry_path: String) {
self.entry_path = Some(entry_path);
}
/// See [`Document::has_data`] for more details.
fn has_data(&self, buf: &[u8]) -> io::Result<bool> {
if buf == br#"{}"#.to_vec() {
return Ok(false);
}
if buf == br#"[]"#.to_vec() {
return Ok(false);
}
Ok(!buf.is_empty())
}
/// See [`Document::read`] for more details.
///
/// # Examples
///
/// ```no_run
/// use chewdata::document::json::Json;
/// use chewdata::document::Document;
/// use serde_json::Value;
///
/// let document = Json::default();
/// let json_str = r#"[{"string":"My text","string_backspace":"My text with \nbackspace","special_char":"€","int":10,"float":9.5,"bool":true}]"#.as_bytes().to_vec();
///
/// let mut dataset = document.read(&json_str).unwrap().into_iter();
/// let data = dataset.next().unwrap().to_value();
/// let expected_data: Value = serde_json::from_slice(&json_str).unwrap();
/// assert_eq!(expected_data, data);
/// ```
#[instrument(skip(buffer), name = "json::read")]
fn read(&self, buffer: &[u8]) -> io::Result<DataSet> {
let deserializer = serde_json::Deserializer::from_reader(io::Cursor::new(buffer));
let iterator = deserializer.into_iter::<Value>();
let mut dataset = Vec::default();
for record_result in iterator {
match (&record_result, &self.entry_path) {
(Ok(record), Some(entry_path)) => match record.clone().search(entry_path)? {
Some(Value::Array(records)) => {
for record in records {
trace!(
record = format!("{:?}", record).as_str(),
"Record deserialized"
);
dataset.push(DataResult::Ok(record));
}
}
Some(record) => {
trace!(
record = format!("{:?}", record).as_str(),
"Record deserialized"
);
dataset.push(DataResult::Ok(record));
}
None => {
warn!(
entry_path = format!("{:?}", entry_path).as_str(),
record = format!("{:?}", &record).as_str(),
"Entry path not found in the record"
);
dataset.push(DataResult::Err((
record.clone(),
io::Error::new(
io::ErrorKind::InvalidInput,
format!("Entry path '{}' not found", entry_path),
),
)));
}
},
(Ok(Value::Array(records)), None) => {
for record in records {
trace!(
record = format!("{:?}", record).as_str(),
"Record deserialized"
);
dataset.push(DataResult::Ok(record.clone()));
}
}
(Ok(record), None) => {
trace!(
record = format!("{:?}", record).as_str(),
"Record deserialized"
);
dataset.push(DataResult::Ok(record.clone()));
}
(Err(e), _) => {
warn!(
error = format!("{:?}", e).as_str(),
"Can't deserialize the record"
);
dataset.push(DataResult::Err((
Value::Null,
io::Error::new(io::ErrorKind::InvalidInput, e.to_string()),
)));
}
};
}
Ok(dataset)
}
/// See [`Document::write`] for more details.
///
/// # Examples
///
/// ```no_run
/// use chewdata::document::json::Json;
/// use chewdata::document::Document;
/// use serde_json::Value;
/// use chewdata::DataResult;
///
/// let mut document = Json::default();
/// let dataset = vec![DataResult::Ok(
/// serde_json::from_str(r#"{"column_1":"line_1"}"#).unwrap(),
/// )];
/// let buffer = document.write(&dataset).unwrap();
/// assert_eq!(r#"{"column_1":"line_1"}"#.as_bytes().to_vec(), buffer);
/// ```
#[instrument(skip(dataset), name = "json::write")]
fn write(&self, dataset: &DataSet) -> io::Result<Vec<u8>> {
let mut buf = Vec::new();
let serialize_value_into_buffer =
|has_terminator: bool, buf: &mut Vec<u8>, value: &Value| -> io::Result<()> {
let mut new_buf = buf;
if has_terminator {
new_buf.append(&mut DEFAULT_TERMINATOR.as_bytes().to_vec());
}
match self.is_pretty {
true => serde_json::to_writer_pretty(&mut new_buf, &value)?,
false => serde_json::to_writer(&mut new_buf, &value)?,
};
trace!(
record = format!("{:?}", value).as_str(),
"Record serialized"
);
Ok(())
};
for (pos, data) in dataset.iter().enumerate() {
let record = data.to_value();
match record {
Value::Array(array) => {
array
.iter()
.enumerate()
.try_for_each(|(array_pos, array_value)| {
serialize_value_into_buffer(pos + array_pos != 0, &mut buf, array_value)
})?;
}
_ => {
serialize_value_into_buffer(pos != 0, &mut buf, &record)?;
}
};
}
Ok(buf)
}
/// See [`Document::header`] for more details.
///
/// # Examples
///
/// ```no_run
/// use chewdata::document::json::Json;
/// use chewdata::document::Document;
///
/// let document = Json::default();
/// let buffer = document.header(&Vec::default()).unwrap();
/// assert_eq!(r#"["#.as_bytes().to_vec(), buffer);
/// ```
fn header(&self, _dataset: &DataSet) -> io::Result<Vec<u8>> {
Ok("[".as_bytes().to_vec())
}
/// See [`Document::footer`] for more details.
///
/// # Examples
///
/// ```no_run
/// use chewdata::document::json::Json;
/// use chewdata::document::Document;
///
/// let document = Json::default();
/// let buffer = document.footer(&Vec::default()).unwrap();
/// assert_eq!(r#"]"#.as_bytes().to_vec(), buffer);
/// ```
fn footer(&self, _dataset: &DataSet) -> io::Result<Vec<u8>> {
Ok("]".as_bytes().to_vec())
}
/// See [`Document::terminator`] for more details.
fn terminator(&self) -> io::Result<Vec<u8>> {
Ok(self
.metadata
.terminator
.clone()
.unwrap_or_else(|| DEFAULT_TERMINATOR.to_string())
.as_bytes()
.to_vec())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn read_data_array() {
let document = Json::default();
let json_str = r#"{"string":"My text","string_backspace":"My text with \nbackspace","special_char":"€","int":10,"float":9.5,"bool":true}"#.as_bytes().to_vec();
let mut dataset = document.read(&json_str).unwrap().into_iter();
let data = dataset.next().unwrap().to_value();
let expected_data: Value = serde_json::from_slice(&json_str).unwrap();
assert_eq!(expected_data, data);
}
#[test]
fn read_data_object() {
let document = Json::default();
let json_str = r#"{"string":"My text","string_backspace":"My text with \nbackspace","special_char":"€","int":10,"float":9.5,"bool":true}"#.as_bytes().to_vec();
let mut dataset = document.read(&json_str).unwrap().into_iter();
let data = dataset.next().unwrap().to_value();
let expected_data: Value = serde_json::from_slice(&json_str).unwrap();
assert_eq!(expected_data, data);
}
#[test]
fn read_empty_data() {
let document = Json::default();
let buffer = Vec::default();
let mut dataset = document.read(&buffer).unwrap().into_iter();
match dataset.next() {
Some(_) => assert!(
false,
"The data read by the json builder should be in error."
),
None => (),
};
}
#[test]
fn read_empty_body() {
let document = Json::default();
let buffer = r#"[]"#.as_bytes().to_vec();
let mut dataset = document.read(&buffer).unwrap().into_iter();
match dataset.next() {
Some(_) => assert!(
false,
"The data read by the json builder should be in error."
),
None => (),
};
}
#[test]
fn read_data_in_target_position() {
let mut document = Json::default();
document.entry_path = Some("/*/array*/*".to_string());
let buffer = r#"[{"array1":[{"field":"value1"},{"field":"value2"}]}]"#
.as_bytes()
.to_vec();
let expected_data: Value = serde_json::from_str(r#"{"field":"value1"}"#).unwrap();
let mut dataset = document.read(&buffer).unwrap().into_iter();
let data = dataset.next().unwrap().to_value();
assert_eq!(expected_data, data);
}
#[test]
fn read_data_without_finding_entry_path() {
let mut document = Json::default();
document.entry_path = Some("/*/not_found/*".to_string());
let buffer = r#"[{"array1":[{"field":"value1"},{"field":"value2"}]}]"#
.as_bytes()
.to_vec();
let expected_data: Value = serde_json::from_str(r#"[{"array1":[{"field":"value1"},{"field":"value2"}]},{"_error":"Entry path '/*/not_found/*' not found"}]"#).unwrap();
let mut dataset = document.read(&buffer).unwrap().into_iter();
let data = dataset.next().unwrap().to_value();
assert_eq!(expected_data, data);
}
#[test]
fn write_object() {
let document = Json::default();
let dataset = vec![
DataResult::Ok(serde_json::from_str(r#"{"column_1":"line_1"}"#).unwrap()),
DataResult::Ok(serde_json::from_str(r#"{"column_1":"line_2"}"#).unwrap()),
];
let buffer = document.write(&dataset).unwrap();
assert_eq!(
r#"{"column_1":"line_1"},{"column_1":"line_2"}"#.as_bytes().to_vec(),
buffer
);
}
#[test]
fn write_array() {
let document = Json::default();
let dataset = vec![
DataResult::Ok(
serde_json::from_str(r#"[{"column_1":"line_1"},{"column_1":"line_2"}]"#).unwrap(),
),
DataResult::Ok(serde_json::from_str(r#"{"column_1":"line_3"}"#).unwrap()),
DataResult::Ok(
serde_json::from_str(r#"[{"column_1":"line_4"},{"column_1":"line_5"}]"#).unwrap(),
),
];
let buffer = document.write(&dataset).unwrap();
assert_eq!(
r#"{"column_1":"line_1"},{"column_1":"line_2"},{"column_1":"line_3"},{"column_1":"line_4"},{"column_1":"line_5"}"#
.as_bytes()
.to_vec(),
buffer
);
}
#[test]
fn write_array_string() {
let document = Json::default();
let dataset = vec![
DataResult::Ok(serde_json::from_str(r#"["a","b"]"#).unwrap()),
DataResult::Ok(serde_json::from_str(r#""c""#).unwrap()),
];
let buffer = document.write(&dataset).unwrap();
assert_eq!(r#""a","b","c""#.as_bytes().to_vec(), buffer);
}
#[test]
fn header() {
let document = Json::default();
let buffer = document.header(&Vec::default()).unwrap();
assert_eq!(r#"["#.as_bytes().to_vec(), buffer);
}
#[test]
fn footer() {
let document = Json::default();
let buffer = document.footer(&Vec::default()).unwrap();
assert_eq!(r#"]"#.as_bytes().to_vec(), buffer);
}
}