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

Swap JSON Objects

See more JSON Examples

Demonstrates how to swap two JSON objects within a JSON document.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

local json = chilkat.JsonObject.new()
json.emit_compact = false

-- Load the following JSON:

-- {
--   "petter": {
--     "DOB": "26/02/1986",
--     "gender": "male",
--     "country": "US"
--   },
--   "Sara": {
--     "DOB": "13/05/1982",
--     "gender": "female",
--     "country": "FR"
--   },
--   "Jon": {
--     "DOB": "19/03/1984",
--     "gender": "male",
--     "country": "UK"
--   }
-- }

local success = json:load_file("qa_data/json/people.json")
if not success then
    print(json.last_error_text)
    return
end

-- Swap the positions of Jon and Sara.
local index1 = json:index_of("Jon")
local index2 = json:index_of("Sara")
json:swap(index1, index2)

-- We have this now:
print(json:emit())

-- {
--   "petter": {
--     "DOB": "26/02/1986",
--     "gender": "male",
--     "country": "US"
--   },
--   "Jon": {
--     "DOB": "19/03/1984",
--     "gender": "male",
--     "country": "UK"
--   },
--   "Sara": {
--     "DOB": "13/05/1982",
--     "gender": "female",
--     "country": "FR"
--   }
-- }

-- To swap an inner member:

local jsonSara = chilkat.JsonObject.new()
json:object_of2("Sara", jsonSara)

index1 = jsonSara:index_of("DOB")
index2 = jsonSara:index_of("country")
jsonSara:swap(index1, index2)

-- We now have this:
print(json:emit())

-- {
--   "petter": {
--     "DOB": "26/02/1986",
--     "gender": "male",
--     "country": "US"
--   },
--   "Jon": {
--     "DOB": "19/03/1984",
--     "gender": "male",
--     "country": "UK"
--   },
--   "Sara": {
--     "country": "FR",
--     "gender": "female",
--     "DOB": "13/05/1982"
--   }
-- }