use crate::jsonish::Value;
use super::{entry, ParseOptions};
use anyhow::Result;
pub fn parse(str: &str, options: &ParseOptions) -> Result<Vec<Value>> {
let mut stack = Vec::new();
let mut json_str_start = None;
let mut json_objects = Vec::new();
for (index, character) in str.char_indices() {
match character {
'{' | '[' => {
if stack.is_empty() {
json_str_start = Some(index);
}
stack.push(character);
}
'}' | ']' => {
if let Some(last) = stack.last() {
let expected_open = if character == '}' { '{' } else { '[' };
if *last == expected_open {
stack.pop();
} else {
return Err(anyhow::anyhow!("Mismatched brackets"));
}
}
if stack.is_empty() {
let end_index = index + 1;
let json_str = if let Some(start) = json_str_start {
&str[start..end_index]
} else {
&str[..end_index]
};
match entry::parse(
json_str,
options.next_from_mode(super::ParsingMode::AllJsonObjects),
) {
Ok(json) => json_objects.push(json),
Err(e) => {
log::error!("Failed to parse JSON object: {:?}", e);
}
}
}
}
_ => {}
}
}
if !stack.is_empty() {
match json_str_start {
Some(start) => {
let json_str = &str[start..];
match entry::parse(
json_str,
options.next_from_mode(super::ParsingMode::AllJsonObjects),
) {
Ok(json) => json_objects.push(json),
Err(e) => {
log::error!("Failed to parse JSON object: {:?}", e);
}
}
}
None => {
log::error!("Unexpected state: stack is not empty but no JSON start was found");
}
}
}
match json_objects.len() {
0 => Err(anyhow::anyhow!("No JSON objects found")),
_ => Ok(json_objects),
}
}