Function extract_json_to_string

Source
pub fn extract_json_to_string(input: &str) -> Result<String, Box<dyn Error>>
Expand description

Extracts JSON from a string and returns the result as a String.

This is a convenience wrapper around JSONParser::extract_json_from_stream that handles buffer management and returns a String directly.

§Arguments

  • input - The string slice containing mixed text and JSON.

§Returns

  • Ok(String) - The extracted JSON as a String.
  • Err(Error) - If an error occurred during parsing or UTF-8 conversion.

§Examples

use surfing::utils::extract_json_to_string;

let input = "Log message: {\"level\":\"info\",\"msg\":\"Hello\"} More text";
let json = extract_json_to_string(input).unwrap();
assert_eq!(json, "{\"level\":\"info\",\"msg\":\"Hello\"}");
use surfing::utils::extract_json_to_string;

// Works with multiple JSON objects
let input = "First: {\"id\":1} Second: {\"id\":2}";
let json = extract_json_to_string(input).unwrap();
assert_eq!(json, "{\"id\":1}{\"id\":2}");
Examples found in repository?
examples/simple.rs (line 21)
8fn main() -> Result<(), Box<dyn std::error::Error>> {
9    // Input containing mixed text and JSON
10    let inputs = [
11        "System log: {\"level\":\"info\",\"component\":\"auth\",\"message\":\"User logged in\"} at 2023-06-15",
12        "Error occurred: {\"code\":500,\"details\":{\"reason\":\"Database connection failed\"}}",
13        "Metrics: [1, 2, 3, 4, 5] recorded at 12:34:56",
14        "Configuration: {\"debug\":true,\"environment\":\"production\"} loaded successfully",
15    ];
16    
17    println!("Extracting JSON from various text inputs:\n");
18    
19    for (i, input) in inputs.iter().enumerate() {
20        // Extract the JSON directly to a string
21        let json = extract_json_to_string(input)?;
22        
23        // Display the results
24        println!("Input {}: {}", i + 1, input);
25        println!("Extracted JSON: {}\n", json);
26    }
27    
28    // You can also chain multiple processing steps
29    let complex_input = "First config: {\"id\":1} Second config: {\"id\":2} Third: {\"id\":3}";
30    println!("Complex input with multiple JSON objects: {}", complex_input);
31    
32    let extracted = extract_json_to_string(complex_input)?;
33    println!("All extracted: {}", extracted);
34    
35    Ok(())
36}