Sample code for 30+ languages & platforms
Rust Requires Chilkat v11.0.0+

Get the Root of a JSON Document

See more JSON Examples

Demonstrates how to get back to the JSON root object from anywhere in the JSON document. This example uses the following JSON document:
{
  "flower": "tulip",
  "abc":
    {
    "x": [
       { "a" : 1 },
       { "b1" : 100, "b2" : 200 },
       { "c" : 3 }
    ],
    "y": 200,
    "z": 200
    }
}

Chilkat Rust Downloads

Rust

let json = chilkat::JsonObject::new();

let json_str = "{\"flower\": \"tulip\",\"abc\":{\"x\": [{ \"a\" : 1 },{ \"b1\" : 100, \"b2\" : 200 },{ \"c\" : 3 }],\"y\": 200,\"z\": 200}}".to_string();

if json.load(&json_str).is_err() {
    println!("{}", json.last_error_text());
    return;
}

// Get the "abc" object.
let abc_obj = chilkat::JsonObject::new();
if json.object_of2("abc", &abc_obj).is_err() {
    println!("{}", json.last_error_text());
    return;
}

// Side note: The JSON of a sub-part of the document can be emitted from any JSON object:
abc_obj.set_emit_compact(false);
println!("{}", abc_obj.emit().unwrap_or_default());

// Navigate to the "x" array
let x_array = chilkat::JsonArray::new();
let _ = abc_obj.array_of2("x", &x_array);

// Navigate to the 2nd object contained within the array.  This contains members b1 and b2
let b_obj = chilkat::JsonObject::new();
let _ = x_array.object_at2(1, &b_obj);

// Show that we're at "b1/b2".
// The value of "b1" should be "200"
println!("b2 = {}", b_obj.int_of("b2"));

// Now go back to the JSON doc root:
let doc_root = chilkat::JsonObject::new();
let _ = b_obj.get_doc_root2(&doc_root);

// We'll skip the null check and assume it's non-null...

// Pretty-print the JSON doc from the root to show that this is indeed the root.
doc_root.set_emit_compact(false);
println!("{}", doc_root.emit().unwrap_or_default());