Lua Requires Chilkat v11.0.0+
Lua
Modify Parts of JSON Document
See more JSON Examples
Demonstrates how to modify parts of a JSON document. This example uses the following JSON document:
{
"fruit": [
{
"kind": "apple",
"count": 24,
"fresh": true,
"extraInfo": null,
"listA": [ "abc", 1, null, false ],
"objectB": { "animal" : "monkey" }
},
{
"kind": "pear",
"count": 18,
"fresh": false,
"extraInfo": null
"listA": [ "xyz", 24, null, true ],
"objectB": { "animal" : "lemur" }
}
],
"list" : [ "banana", 12, true, null, "orange", 12.5, { "ticker": "AAPL" }, [ 1, 2, 3, 4, 5 ] ],
"alien" : true
}
Chilkat Lua Downloads
local chilkat = require("chilkat")
local json = chilkat.JsonObject.new()
-- Load the JSON from a file.
local success = json:load_file("qa_data/json/modifySample.json")
if not success then
print(json.last_error_text)
return
end
-- This example will not check for errors (i.e. null / false / 0 return values)...
-- Get the "list" array:
local listA = chilkat.JsonArray.new()
json:array_of2("list", listA)
-- Modify values in the list.
-- Change banana to plantain
success = listA:set_string_at(0, "plantain")
-- Change 12 to 24
success = listA:set_int_at(1, 24)
-- Change true to false
success = listA:set_bool_at(2, false)
-- Is the 3rd item null?
local bNull = listA:is_null_at(3)
-- Change "orange" to 32.
success = listA:set_int_at(4, 32)
-- Change 12.5 to 31.2
success = listA:set_number_at(5, "31.2")
-- Replace the { "ticker" : "AAPL" } object with { "ticker" : "GOOG" }
-- Do this by deleting, then inserting a new object at the same location.
success = listA:delete_at(6)
local tickerObj = chilkat.JsonObject.new()
listA:add_object_at2(6, tickerObj)
success = tickerObj:append_string("ticker", "GOOG")
-- Replace "[ 1, 2, 3, 4, 5 ]" with "[ "apple", 22, true, null, 1080.25 ]"
success = listA:delete_at(7)
local aa = chilkat.JsonArray.new()
listA:add_array_at2(7, aa)
success = aa:add_string_at(-1, "apple")
success = aa:add_int_at(-1, 22)
success = aa:add_bool_at(-1, true)
success = aa:add_null_at(-1)
success = aa:add_number_at(-1, "1080.25")
-- Get the "fruit" array
local aFruit = chilkat.JsonArray.new()
json:array_at2(0, aFruit)
-- Get the 1st element:
local appleObj = chilkat.JsonObject.new()
aFruit:object_at2(0, appleObj)
-- Modify values by member name:
success = appleObj:set_string_of("fruit", "fuji_apple")
success = appleObj:set_int_of("count", 46)
success = appleObj:set_bool_of("fresh", false)
success = appleObj:set_string_of("extraInfo", "developed by growers at the Tohoku Research Station in Fujisaki")
-- Modify values by index:
local pearObj = chilkat.JsonObject.new()
aFruit:object_at2(1, pearObj)
success = pearObj:set_string_at(0, "bartlett_pear")
success = pearObj:set_int_at(1, 12)
success = pearObj:set_bool_at(2, false)
success = pearObj:set_string_at(3, "harvested in late August to early September")
json.emit_compact = false
print(json:emit())