### Iterate Over JSON Lists and Objects in Rust with yyjson-rs Source: https://github.com/bnmoch3/yyjson-rs/blob/master/README.md Shows how to iterate over JSON arrays and objects parsed by yyjson-rs. This example demonstrates accessing elements within a list by index and iterating through key-value pairs in an object. Assumes a `yyjson_rs::Doc` object is already available. ```rust // Array iteration let scores = root.at_key("scores").and_then(|v| v.list()).unwrap(); for score in scores.iter() { println!("Score: {}", score.f64().unwrap()); } // Object iteration let metadata = root.at_key("metadata").and_then(|v| v.obj()).unwrap(); for (key, value) in metadata.iter() { println!("{}: {}", key, value); } ``` -------------------------------- ### Demonstrate yyjson-rs Memory Allocation Strategies Source: https://context7.com/bnmoch3/yyjson-rs/llms.txt This snippet demonstrates the three memory allocator strategies provided by yyjson-rs: BasicAllocProvider (default libc), PoolAllocProvider (fixed pre-allocated buffer), and DynamicAllocProvider (grows dynamically). It shows how to initialize and use each provider with DocContext for JSON parsing. ```rust use yyjson_rs::{ BasicAllocProvider, DocContext, DynamicAllocProvider, PoolAllocProvider, ReadOptions, YyjsonAllocProvider, }; fn main() -> Result<(), Box> { let json = r#"{"key": "value", "numbers": [1, 2, 3]}"#; // 1. BasicAllocProvider - uses libc malloc/free (default) { let ctx = DocContext::default(); // Uses BasicAllocProvider let doc = ctx.parse(json.as_bytes())?; println!("Basic: {:?}", doc.root().at_key("key").and_then(|v| v.str())); } // 2. PoolAllocProvider - pre-allocated fixed buffer (best for known sizes) { let expected_size = json.len(); let pool = PoolAllocProvider::new(expected_size, None)?; let ctx = DocContext::new(pool, ReadOptions::default()); let doc = ctx.parse(json.as_bytes())?; println!("Pool: {:?}", doc.root().at_key("key").and_then(|v| v.str())); } // 3. DynamicAllocProvider - grows as needed, frees all on drop { let dynamic = DynamicAllocProvider::default(); let ctx = DocContext::new(dynamic, ReadOptions::default()); let doc = ctx.parse(json.as_bytes())?; println!("Dynamic: {:?}", doc.root().at_key("key").and_then(|v| v.str())); } Ok(()) } ``` -------------------------------- ### Writing JSON with Writer and WriteOptions in Rust Source: https://context7.com/bnmoch3/yyjson-rs/llms.txt Details how to serialize parsed JSON documents back into strings using `yyjson-rs`'s `Writer`. It covers configuring `WriteOptions` for pretty printing, unicode escaping, and handling Inf/NaN values. Requires the `yyjson_rs` crate. ```rust use yyjson_rs::{ BasicAllocProvider, DocContext, ReadOptions, WriteOptions, Writer, YyjsonAllocProvider, }; fn main() -> Result<(), Box> { // Parse a document let json = r#"{"name": "John", "age": 30, "scores": [95.5, 89.2]}"#; let ctx = DocContext::default(); let doc = ctx.parse(json.as_bytes())?; // Configure write options for pretty output let write_opts = WriteOptions { pretty: true, // 4-space indentation pretty_with_two_spaces: false, // Use 2-space instead (overrides pretty) escape_unicode: false, // Keep unicode characters escape_slashes: false, // Don't escape forward slashes allow_inf_and_nan: false, // Error on Inf/NaN inf_and_nan_as_null: false, // Write Inf/NaN as null add_newline_at_end: false, // For NDJSON }; // Create writer with allocator let alloc_provider = BasicAllocProvider::default(); let allocator = alloc_provider.get_allocator(); let mut writer = Writer::new(allocator, Some(&write_opts)); // Write document to string let output = doc.write(&mut writer)?; println!("Pretty JSON:\n{}", output.as_str()); // Output: // { // "name": "John", // "age": 30, // "scores": [ // 95.5, // 89.2 // ] // } // Access raw bytes if needed let bytes: &[u8] = output.as_bytes(); println!("Output length: {} bytes", bytes.len()); Ok(()) } ``` -------------------------------- ### Write and Format JSON in Rust using yyjson-rs Source: https://github.com/bnmoch3/yyjson-rs/blob/master/README.md Illustrates writing JSON data to a string using yyjson-rs, including parsing a potentially non-standard JSON string with comments and NaN values. It configures read and write options for handling these cases and demonstrates pretty-printing the output. Requires `yyjson-rs` and `anyhow`. ```rust use yyjson_rs::{ BasicAllocProvider, DocContext, ReadOptions, WriteOptions, Writer, YyjsonAllocProvider, }; fn main() -> Result<(), Box> { // parse doc let json = r#"{"name": "John", /* age is invalid */ "age": NaN,}""#; let read_opts = ReadOptions { allow_trailing_commas: true, allow_comments: true, allow_inf_and_nan: true, ..Default::default() }; let doc_context = DocContext::new(BasicAllocProvider::default(), read_opts); let doc = doc_context.parse(json.as_bytes())?; // write let alloc_provider = BasicAllocProvider::default(); let allocator = alloc_provider.get_allocator(); let write_opts = WriteOptions { pretty: true, allow_inf_and_nan: true, ..Default::default() }; let mut writer = Writer::new(allocator, Some(&write_opts)); let output = doc.write(&mut writer)?; println!("{}", output.as_str()); Ok(()) } ``` -------------------------------- ### Parsing Non-Standard JSON with ReadOptions in Rust Source: https://context7.com/bnmoch3/yyjson-rs/llms.txt Explains how to use `ReadOptions` with `yyjson-rs` to parse JSON that deviates from the standard. This includes handling trailing commas, C-style comments, Inf/NaN values, and optionally treating big numbers as raw strings. Requires the `yyjson_rs` crate. ```rust use yyjson_rs::{BasicAllocProvider, DocContext, ReadOptions, YyjsonAllocProvider}; fn main() -> Result<(), Box> { // Non-standard JSON with comments, trailing comma, and NaN let json = r#"{ "name": "John", /* This is a comment */ "value": NaN, "items": [1, 2, 3,], // trailing comma }"#; // Configure read options for non-standard JSON let read_opts = ReadOptions { allow_trailing_commas: true, allow_comments: true, allow_inf_and_nan: true, stop_when_done: false, bignums_as_raw_strings: false, }; let doc_context = DocContext::new(BasicAllocProvider::default(), read_opts); let doc = doc_context.parse(json.as_bytes())?; let root = doc.root(); println!("Name: {:?}", root.at_key("name").and_then(|v| v.str())); // Output: Name: Some("John") let value = root.at_key("value").and_then(|v| v.f64()); println!("Value is NaN: {}", value.map(|v| v.is_nan()).unwrap_or(false)); // Output: Value is NaN: true let items = root.at_key("items").and_then(|v| v.list()).unwrap(); println!("Items count: {}", items.len()); // Output: Items count: 3 Ok(()) } ``` -------------------------------- ### Navigate Nested JSON Structures in Rust Source: https://context7.com/bnmoch3/yyjson-rs/llms.txt Illustrates how to traverse deeply nested JSON objects and arrays using chained `at_key()` and `at_index()` calls on `Val` objects. It demonstrates type-safe accessors for strings, booleans, and numeric values within the nested structure. ```rust use yyjson_rs::DocContext; fn main() -> Result<(), Box> { let json = r#"{ "user": { "profile": { "name": "Bob", "verified": true }, "scores": [100, 200, 300] } }"#; let ctx = DocContext::default(); let doc = ctx.parse(json.as_bytes())?; let root = doc.root(); // Chain at_key() calls to navigate nested objects let name = root .at_key("user") .and_then(|u| u.at_key("profile")) .and_then(|p| p.at_key("name")) .and_then(|n| n.str()); println!("Name: {:?}", name); // Output: Name: Some("Bob") // Access boolean values let verified = root .at_key("user") .and_then(|u| u.at_key("profile")) .and_then(|p| p.at_key("verified")) .and_then(|v| v.bool()); println!("Verified: {:?}", verified); // Output: Verified: Some(true) // Access array elements by index let second_score = root .at_key("user") .and_then(|u| u.at_key("scores")) .and_then(|s| s.at_index(1)) .and_then(|v| v.u64()); println!("Second score: {:?}", second_score); // Output: Second score: Some(200) Ok(()) } ``` -------------------------------- ### Working with Objects (Obj) in Rust Source: https://context7.com/bnmoch3/yyjson-rs/llms.txt Demonstrates how to use the `Obj` type in yyjson-rs for object/map access. It covers key-based lookup, iteration over entries and keys, and using an ordered getter for optimized sequential access. Requires the `yyjson_rs` crate. ```rust use yyjson_rs::DocContext; fn main() -> Result<(), Box> { let json = r#"{"a": 10, "b": 20, "c": 30, "d": 40, "e": 50}"#; let ctx = DocContext::default(); let doc = ctx.parse(json.as_bytes())?; let root = doc.root(); // Convert Val to Obj let obj = root.obj().unwrap(); // Check length println!("Length: {}", obj.len()); // Output: 5 println!("Is empty: {}", obj.is_empty()); // Output: false // Access values by key println!("Key 'a': {:?}", obj.get("a").and_then(|v| v.u64())); // Output: Some(10) println!("Key 'c': {:?}", obj.get("c").and_then(|v| v.u64())); // Output: Some(30) println!("Key 'x': {:?}", obj.get("x")); // Output: None // Iterate over key-value pairs println!("All entries:"); for (key, value) in obj.iter() { println!(" {}: {}", key, value.u64().unwrap()); } // Iterate over keys only let keys: Vec<&str> = obj.keys().collect(); println!("Keys: {:?}", keys); // Output: Keys: ["a", "b", "c", "d", "e"] // Ordered getter for sequential access (faster for ordered lookups) let mut getter = obj.ordered_getter(); println!("Ordered access 'a': {:?}", getter.get("a").and_then(|v| v.u64())); println!("Ordered access 'b': {:?}", getter.get("b").and_then(|v| v.u64())); Ok(()) } ``` -------------------------------- ### Work with JSON Arrays (List) in Rust Source: https://context7.com/bnmoch3/yyjson-rs/llms.txt Demonstrates how to handle JSON arrays using the `List` type in `yyjson-rs`. It covers checking array length, emptiness, accessing elements by index, iterating over elements, and collecting them into a `Vec`. ```rust use yyjson_rs::DocContext; fn main() -> Result<(), Box> { let json = r#"[10, 20, 30, 40, 50]"#; let ctx = DocContext::default(); let doc = ctx.parse(json.as_bytes())?; let root = doc.root(); // Convert Val to List let list = root.list().unwrap(); // Check length and emptiness println!("Length: {}", list.len()); // Output: 5 println!("Is empty: {}", list.is_empty()); // Output: false // Access elements by index println!("First: {:?}", list.first().and_then(|v| v.u64())); // Output: Some(10) println!("Last: {:?}", list.last().and_then(|v| v.u64())); // Output: Some(50) println!("Index 2: {:?}", list.get(2).and_then(|v| v.u64())); // Output: Some(30) println!("Index 10: {:?}", list.get(10)); // Output: None (out of bounds) // Iterate over all elements print!("All values: "); for val in list.iter() { print!("{} ", val.u64().unwrap()); } println!(); // Output: All values: 10 20 30 40 50 // Collect into a Vec let values: Vec = list.iter().filter_map(|v| v.u64()).collect(); println!("Collected: {:?}", values); // Output: Collected: [10, 20, 30, 40, 50] Ok(()) } ``` -------------------------------- ### Parse JSON with DocContext in Rust Source: https://context7.com/bnmoch3/yyjson-rs/llms.txt Demonstrates parsing a JSON string using `DocContext` and accessing primitive values like strings and numbers from the root of the parsed document. It utilizes `DocContext::default()` for basic memory allocation and `parse()` to create a `Doc` object. ```rust use yyjson_rs::DocContext; fn main() -> Result<(), Box> { let json = r#"{ "name": "Alice", "age": 30, "scores": [95.5, 89.2, 92.8], "metadata": { "active": true, "tags": ["rust", "c", "json"] } }"#; // Create a default context with BasicAllocProvider let ctx = DocContext::default(); // Parse JSON bytes into a document let doc = ctx.parse(json.as_bytes())?; // Get root value to start navigating let root = doc.root(); // Access primitive values using at_key() and type extractors let name: Option<&str> = root.at_key("name").and_then(|v| v.str()); let age: Option = root.at_key("age").and_then(|v| v.u64()); println!("Name: {:?}, Age: {:?}", name, age); // Output: Name: Some("Alice"), Age: Some(30) // Document metadata println!("Read size: {} bytes", doc.read_size()); println!("Value count: {}", doc.val_count()); Ok(()) } ``` -------------------------------- ### Parse JSON String in Rust using yyjson-rs Source: https://github.com/bnmoch3/yyjson-rs/blob/master/README.md Demonstrates parsing a JSON string into a document object using yyjson-rs. It shows how to access primitive values, navigate nested structures like lists and objects, and retrieve specific data types such as strings, numbers, and booleans. Requires the `yyjson-rs` crate. ```rust use yyjson_rs::DocContext; fn main() -> anyhow::Result<()> { let json = r#" { "name": "Alice", "age": 30, "scores": [95.5, 89.2, 92.8], "metadata": { "active": true, "tags": ["rust", "c", "json"] } }" #; let ctx = DocContext::default(); let doc = ctx.parse(json.as_bytes())?; let root = doc.root(); // Access primitive values let name: Option<&str> = root.at_key("name").and_then(|v| v.str()); let age: Option = root.at_key("age").and_then(|v| v.u64()); // Navigate nested structures let scores = root.at_key("scores").and_then(|v| v.list()).unwrap(); let first_score = scores.get(0).and_then(|v| v.f64()).unwrap(); let active: Option = root .at_key("metadata") .and_then(|m| m.at_key("active")) .unwrap() .bool(); Ok(()) } ``` -------------------------------- ### Perform yyjson-rs Value Type Checking and Extraction Source: https://context7.com/bnmoch3/yyjson-rs/llms.txt This snippet demonstrates how to check the type of JSON values using `get_type()` and safely extract them using type-specific methods like `bool()`, `u64()`, `i64()`, and `f64()` which return `Option`. ```rust use yyjson_rs::{DocContext, ValType}; fn main() -> Result<(), Box> { let json = r#"{ "null_val": null, "bool_val": true, "uint_val": 42, "int_val": -100, "float_val": 3.14, "str_val": "hello", "list_val": [1, 2, 3], "obj_val": {"nested": true} }"#; let ctx = DocContext::default(); let doc = ctx.parse(json.as_bytes())?; let root = doc.root(); // Check types using get_type() let null_val = root.at_key("null_val").unwrap(); assert_eq!(null_val.get_type(), ValType::Null); let bool_val = root.at_key("bool_val").unwrap(); assert_eq!(bool_val.get_type(), ValType::Bool); println!("Bool: {:?}", bool_val.bool()); // Output: Some(true) let uint_val = root.at_key("uint_val").unwrap(); assert_eq!(uint_val.get_type(), ValType::UInt64); println!("UInt: {:?}", uint_val.u64()); // Output: Some(42) let int_val = root.at_key("int_val").unwrap(); assert_eq!(int_val.get_type(), ValType::Int64); println!("Int: {:?}", int_val.i64()); // Output: Some(-100) let float_val = root.at_key("float_val").unwrap(); assert_eq!(float_val.get_type(), ValType::Float64); println!("Float: {:?}", float_val.f64()); // Output: Some(3.14) // f64_or_NAN returns NAN if not a float let str_val = root.at_key("str_val").unwrap(); println!("String as f64: {}", str_val.f64_or_NAN()); // Output: NaN let list_val = root.at_key("list_val").unwrap(); assert_eq!(list_val.get_type(), ValType::List); let obj_val = root.at_key("obj_val").unwrap(); assert_eq!(obj_val.get_type(), ValType::Obj); Ok(()) } ``` -------------------------------- ### Handle yyjson-rs JSON Parsing Errors Source: https://context7.com/bnmoch3/yyjson-rs/llms.txt This snippet illustrates how to handle errors during JSON parsing with yyjson-rs. It demonstrates catching specific `ReadError` variants, checking for memory allocation failures, and successfully parsing valid JSON. ```rust use yyjson_rs::{DocContext, ReadError, ReadCode}; fn main() { let ctx = DocContext::default(); // Invalid JSON - missing closing brace let invalid_json = r#"{"name": "test""#; match ctx.parse(invalid_json.as_bytes()) { Ok(doc) => println!("Parsed: {}", doc), Err(ReadError::OnRead { code, msg, pos }) => { println!("Parse error at position {}: {} ({:?})", pos, msg, code); // Output: Parse error at position 15: unexpected end of data (ErrorUnexpectedEnd) } Err(e) => println!("Other error: {}", e), } // Check for specific error types let result = ctx.parse(b""); if let Err(ref e) = result { if e.is_mem_allocation_err() { println!("Memory allocation failed"); } } // Valid JSON parses successfully let valid_json = r#"{"name": "test"}"#; match ctx.parse(valid_json.as_bytes()) { Ok(doc) => { let name = doc.root().at_key("name").and_then(|v| v.str()); println!("Success: name = {:?}", name); // Output: Success: name = Some("test") } Err(e) => println!("Error: {}", e), } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.