Sample code for 30+ languages & platforms
Rust

JSON: Array of Objects

See more JSON Examples

Here we have a JSON object that contains an array, where each element in the array is a JSON object. This example demonstrates how to access the objects contained within an array.
{ 
  "employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter","lastName":"Jones"}
  ]
}

Chilkat Rust Downloads

Rust

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

// This is the above JSON with whitespace chars removed (SPACE, TAB, CR, and LF chars).
// The presence of whitespace chars for pretty-printing makes no difference to the Load
// method. 
let json_str = "{\"employees\":[{\"firstName\":\"John\", \"lastName\":\"Doe\"},{\"firstName\":\"Anna\", \"lastName\":\"Smith\"},{\"firstName\":\"Peter\",\"lastName\":\"Jones\"}]}".to_string();

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

// Get the "employees" array.
let employees = json.array_of("employees").unwrap();
if !json.last_method_success() {
    println!("employees member not found.");
    return;
}

// Iterate over each employee, getting the JSON object at each index.
let num_employees = employees.size();
let mut i = 0;
while i < num_employees {

    let emp_obj = employees.object_at(i).unwrap();

    println!("employee[{}] = {} {}", i, emp_obj.string_of("firstName").unwrap_or_default(), emp_obj.string_of("lastName").unwrap_or_default());

    i = i + 1;
}