Sample code for 30+ languages & platforms
Lua

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 Lua Downloads

Lua
local chilkat = require("chilkat")

local 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.
local jsonStr = "{\"employees\":[{\"firstName\":\"John\", \"lastName\":\"Doe\"},{\"firstName\":\"Anna\", \"lastName\":\"Smith\"},{\"firstName\":\"Peter\",\"lastName\":\"Jones\"}]}"

local success = json:load(jsonStr)
if not success then
    print(json.last_error_text)
    return
end

-- Get the "employees" array.
local employees = json:array_of("employees")
if not json.last_method_success then
    print("employees member not found.")
    return
end

-- Iterate over each employee, getting the JSON object at each index.
local numEmployees = employees.size
local i = 0
while i < numEmployees do
    local empObj = employees:object_at(i)

    print("employee[" .. i .. "] = " .. empObj:string_of("firstName") .. " " .. empObj:string_of("lastName"))

    i = i + 1
end