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

JSON: Miscellaneous Operations

See more JSON Examples

Demonstrates a variety of JSON API methods. This example uses the following JSON document:
{
   "alphabet": "abcdefghijklmnopqrstuvwxyz",
   "sampleData" : {
           "pi": 3.14,
	   "apple": "juicy",
	   "hungry": true,
	   "withoutValue": null,
           "answer": 42
          
	}
}

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

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

-- Assume the file contains the data as shown above..
local success = json:load_file("qa_data/json/sample2.json")
if not success then
    print(json.last_error_text)
    return
end

-- Get the "sampleData" object:
local sampleData = chilkat.JsonObject.new()
json:object_of2("sampleData", sampleData)

-- Demonstrate BoolAt and BoolOf
print("hungry: " .. tostring(sampleData:bool_of("hungry")))
print("hungry: " .. tostring(sampleData:bool_at(2)))

-- StringOf returns the value as a string regardless of it's actual type:
print("pi: " .. sampleData:string_of("pi"))
print("answer: " .. sampleData:string_of("answer"))
print("withoutValue: " .. sampleData:string_of("withoutValue"))
print("hungry: " .. sampleData:string_of("hungry"))

-- Demonstrate IsNullOf / IsNullAt
print("withoutValue is null? " .. tostring(sampleData:is_null_of("withoutValue")))
print("withoutValue is null? " .. tostring(sampleData:is_null_at(3)))
print("apple is null? " .. tostring(sampleData:is_null_of("apple")))
print("apple is null? " .. tostring(sampleData:is_null_at(1)))

-- IntOf
print("answer: " .. sampleData:int_of("answer"))

-- SetNullAt, SetNullOf
-- Set "pi" to null
success = sampleData:set_null_at(0)
-- Set "answer" to null
success = sampleData:set_null_of("answer")

-- Show the changes:
print(json:emit())

-- Restore pi and apple:
success = sampleData:set_number_at(0, "3.14")
success = sampleData:set_number_of("answer", "42")

-- Show the changes:
print(json:emit())

-- Add a null value named "afterApple" just after "apple"
success = sampleData:add_null_at(2, "afterApple")

-- Add a boolean value just after "pi"
success = sampleData:add_bool_at(1, "afterPi", false)

-- Examine the changes..
print(json:emit())