Rust Requires Chilkat v11.0.0+
Rust
JSON: Miscellaneous Operations
See more JSON Examples
Demonstrates a variety of JSON API methods. This example uses the following JSON document:
{
"alphabet": "abcdefghijklmnopqrstuvwxyz",
"sampleData" : {
"pi": 3.14,
"apple": "juicy",
"hungry": true,
"withoutValue": null,
"answer": 42
}
}
Chilkat Rust Downloads
let json = chilkat::JsonObject::new();
json.set_emit_compact(false);
// Assume the file contains the data as shown above..
if json.load_file("qa_data/json/sample2.json").is_err() {
println!("{}", json.last_error_text());
return;
}
// Get the "sampleData" object:
let sample_data = chilkat::JsonObject::new();
let _ = json.object_of2("sampleData", &sample_data);
// Demonstrate BoolAt and BoolOf
println!("hungry: {}", sample_data.bool_of("hungry"));
println!("hungry: {}", sample_data.bool_at(2));
// StringOf returns the value as a string regardless of it's actual type:
println!("pi: {}", sample_data.string_of("pi").unwrap_or_default());
println!("answer: {}", sample_data.string_of("answer").unwrap_or_default());
println!("withoutValue: {}", sample_data.string_of("withoutValue").unwrap_or_default());
println!("hungry: {}", sample_data.string_of("hungry").unwrap_or_default());
// Demonstrate IsNullOf / IsNullAt
println!("withoutValue is null? {}", sample_data.is_null_of("withoutValue"));
println!("withoutValue is null? {}", sample_data.is_null_at(3));
println!("apple is null? {}", sample_data.is_null_of("apple"));
println!("apple is null? {}", sample_data.is_null_at(1));
// IntOf
println!("answer: {}", sample_data.int_of("answer"));
// SetNullAt, SetNullOf
// Set "pi" to null
let _ = sample_data.set_null_at(0).is_ok();
// Set "answer" to null
let _ = sample_data.set_null_of("answer").is_ok();
// Show the changes:
println!("{}", json.emit().unwrap_or_default());
// Restore pi and apple:
let _ = sample_data.set_number_at(0, "3.14").is_ok();
let _ = sample_data.set_number_of("answer", "42").is_ok();
// Show the changes:
println!("{}", json.emit().unwrap_or_default());
// Add a null value named "afterApple" just after "apple"
let _ = sample_data.add_null_at(2, "afterApple").is_ok();
// Add a boolean value just after "pi"
let _ = sample_data.add_bool_at(1, "afterPi", false).is_ok();
// Examine the changes..
println!("{}", json.emit().unwrap_or_default());