Sample code for 30+ languages & platforms
Lua

Loading and Parsing a JSON Array

See more JSON Examples

A JSON array is JSON that begins with "[" and ends with "]". For example, this is a JSON array that contains 3 JSON objects.
[{"name":"jack"},{"name":"john"},{"name":"joe"}]
A JSON object, however, is JSON that begins with "{" and ends with "}". For example, this JSON is an object that contains an array.
{"pets":[{"name":"jack"},{"name":"john"},{"name":"joe"}]}
This example shows how loading a JSON array is different than loading a JSON object.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

local strJsonArray = "[{\"name\":\"jack\"},{\"name\":\"john\"},{\"name\":\"joe\"}]"

local strJsonObject = "{\"pets\":[{\"name\":\"jack\"},{\"name\":\"john\"},{\"name\":\"joe\"}]}"

-- A JSON array must be loaded using JsonArray:
local jsonArray = chilkat.JsonArray.new()
jsonArray:load(strJsonArray)

-- Examine the values:
local i = 0
while i < jsonArray.size do
    local jsonObj = jsonArray:object_at(i)
    print(i .. ": " .. jsonObj:string_of("name"))

    i = i + 1
end

-- Output is:

--     0: jack
--     1: john
--     2: joe

-- A JSON object must be loaded using JsonObject
local jsonObject = chilkat.JsonObject.new()
jsonObject:load(strJsonObject)

-- Examine the values:
i = 0
local numPets = jsonObject:size_of_array("pets")
while i < numPets do
    jsonObject.i = i
    print(i .. ": " .. jsonObject:string_of("pets[i].name"))
    i = i + 1
end

-- Output is:

--     0: jack
--     1: john
--     2: joe