json.rs

Overview

The `json.rs` file provides a Rust-based fallback JSON deserialization backend that converts JSON text into Python objects. It is part of a larger JSON parsing system designed to optionally use a high-performance C-based parser (`yyjson`) when enabled, or this Rust fallback parser otherwise.

This file leverages the `serde_json` crate for parsing JSON strings and implements a custom visitor pattern (`JsonValue`) to recursively translate JSON primitives, arrays, and objects into Python-native data structures, represented as raw pointers (`NonNull`) to Python objects managed via the PyO3 FFI layer.

The fallback parser ensures broad compatibility and ease of maintenance when the `yyjson` feature flag is disabled, providing a robust deserialization path that integrates with error handling and the Python runtime environment.


Detailed Documentation

Functions


deserialize

pub(crate) fn deserialize(
    data: &'static str,
) -> Result<NonNull<pyo3_ffi::PyObject>, DeserializeError<'static>>
let json_text = r#"{"key": "value", "list": [1, 2, 3]}"#;
match deserialize(json_text) {
    Ok(py_obj_ptr) => {
        // Use py_obj_ptr via FFI in Python environment
    }
    Err(e) => {
        eprintln!("Deserialization failed: {}", e);
    }
}

Structs


JsonValue

#[derive(Clone, Copy)]
struct JsonValue;

deserialize
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
    D: Deserializer<'de>;

expecting
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result;

Visitor Methods

These methods correspond to JSON types and convert them to Python objects:


Important Implementation Details


Interaction with Other System Components


Usage Example: Deserializing JSON Text to Python Object

use crate::deserialize::json::deserialize;

fn main() {
    let json_data = r#"{"name": "Alice", "age": 30, "likes": ["rust", "python"]}"#;

    match deserialize(json_data) {
        Ok(py_obj_ptr) => {
            // py_obj_ptr points to a Python dict representing the JSON data.
            // Further manipulation or FFI calls can be made here.
        }
        Err(err) => {
            eprintln!("Failed to parse JSON: {}", err);
        }
    }
}

Mermaid Diagram: Structure of json.rs

classDiagram
    class JsonValue {
        +deserialize<D>(deserializer: D) Result<NonNull<PyObject>, D::Error>
        +expecting(formatter: &mut fmt::Formatter) fmt::Result
        +visit_unit() Result<NonNull<PyObject>, E>
        +visit_bool(value: bool) Result<NonNull<PyObject>, E>
        +visit_i64(value: i64) Result<NonNull<PyObject>, E>
        +visit_u64(value: u64) Result<NonNull<PyObject>, E>
        +visit_f64(value: f64) Result<NonNull<PyObject>, E>
        +visit_borrowed_str(value: &str) Result<NonNull<PyObject>, E>
        +visit_str(value: &str) Result<NonNull<PyObject>, E>
        +visit_seq(seq: SeqAccess) Result<NonNull<PyObject>, E>
        +visit_map(map: MapAccess) Result<NonNull<PyObject>, E>
    }

    class json_rs {
        +deserialize(data: &str) Result<NonNull<PyObject>, DeserializeError>
    }

    json_rs --> JsonValue : uses

Summary

The `json.rs` file implements a robust Rust fallback JSON deserialization backend that transforms JSON text into Python objects using Serde's deserialization framework. It provides comprehensive coverage for all JSON data types, converting them into corresponding Python objects via the PyO3 FFI layer. This backend is integral to the JSON parsing subsystem when the `yyjson` feature is disabled, ensuring compatibility and maintainability without sacrificing correctness or error transparency. The design prioritizes safe pointer handling, efficient memory usage, and clear error propagation, making it a reliable core component of the JSON deserialization infrastructure.