JSON

Parse and generate JSON data for configuration and API responses.

json.parse

Signature: json.parse(data)

Description: Parses a JSON-encoded string and returns a Lua table.

Parameters:

  • data (string): The JSON-encoded string to parse.

Returns:

  • table: A Lua table representation of the JSON data.

Example:

local json_string = '{"name": "Lua API", "version": 1.0, "features": ["json", "parsing", "serialization"]}'
local data = json.parse(json_string)

engine.log("Name: " .. data.name, 255, 255, 255, 255)
engine.log("Version: " .. data.version, 255, 255, 255, 255)
engine.log("Features count: " .. #data.features, 255, 255, 255, 255)
engine.log("First feature: " .. data.features[1], 255, 255, 255, 255)

json.stringify

Signature: json.stringify(lua_table)

Description: Converts a Lua table into a JSON-formatted string with indentation.

Parameters:

  • lua_table (table): The Lua table to convert to JSON.

Returns:

  • string: A JSON-formatted string representing the Lua table.

Example:

local data = {
    name = "Lua API",
    version = 1.5,
    features = {"json", "parsing", "serialization"},
    settings = {
        debug = true,
        max_depth = 10
    }
}

local json_string = json.stringify(data)
engine.log("Generated JSON:", 255, 255, 255, 255)
engine.log(json_string, 255, 255, 255, 255)

JSON API Usage Examples

Reading and Writing JSON Configuration

-- Function to load configuration from a JSON file
function load_config(config_file)
    if not fs.does_file_exist(config_file) then
        engine.log("Config file not found: " .. config_file, 255, 0, 0, 255)
        return nil
    end
    
    local json_string = fs.read_from_file(config_file)
    if not json_string then
        engine.log("Failed to read config file", 255, 0, 0, 255)
        return nil
    end
    
    local config = json.parse(json_string)
    engine.log("Config loaded successfully", 0, 255, 0, 255)
    return config
end

-- Function to save configuration to a JSON file
function save_config(config, config_file)
    local json_string = json.stringify(config)
    
    local success = fs.write_to_file(config_file, json_string)
    if success then
        engine.log("Config saved successfully", 0, 255, 0, 255)
    else
        engine.log("Failed to save config", 255, 0, 0, 255)
    end
    
    return success
end

-- Example usage
local config_path = "settings.json"
local config = load_config(config_path)

if not config then
    -- Create default config if none exists
    config = {
        user = {
            name = "Default User",
            theme = "dark"
        },
        app = {
            version = "1.0",
            debug = false,
            window_size = {width = 800, height = 600}
        }
    }
    
    save_config(config, config_path)
else
    -- Modify and save the config
    config.user.theme = "light"
    config.app.debug = true
    
    save_config(config, config_path)
end

Working with API Responses

-- Function to handle a network response containing JSON data
function handle_json_response(response_data, url)
    local response_string = m.read_string(response_data, 0)
    
    -- Try to parse the JSON
    local success, result = pcall(function()
        return json.parse(response_string)
    end)
    
    if not success then
        engine.log("Failed to parse JSON response: " .. tostring(result), 255, 0, 0, 255)
        return
    end
    
    -- Process the parsed JSON data
    engine.log("API Response processed successfully", 0, 255, 0, 255)
    
    if result.status == "success" then
        if result.data and result.data.items then
            engine.log("Received " .. #result.data.items .. " items", 255, 255, 255, 255)
            
            -- Process each item
            for i, item in ipairs(result.data.items) do
                engine.log("Item " .. i .. ": " .. item.name, 255, 255, 255, 255)
            end
        end
    else
        engine.log("API Error: " .. (result.error or "Unknown error"), 255, 0, 0, 255)
    end
end

-- Register the response handler
engine.register_on_network_callback(handle_json_response)

-- Send a request to an API that returns JSON
function request_api_data()
    local url = "https://api.example.com/data"
    local headers = "Content-Type: application/json\r\nUser-Agent: LuaAPI/1.0"
    
    net.send_request(url, headers)
    engine.log("Request sent to: " .. url, 255, 255, 255, 255)
end

-- Call the function to initiate the request
request_api_data()

Creating Complex JSON Structures

-- Create a complex data structure
local game_state = {
    player = {
        name = "Player1",
        position = {x = 100.5, y = 200.75, z = 50.25},
        health = 85,
        inventory = {
            {id = "sword", level = 2, enchanted = true},
            {id = "shield", level = 1, enchanted = false},
            {id = "potion", count = 5}
        }
    },
    world = {
        name = "Test World",
        seed = 12345678,
        dimensions = {
            overworld = {loaded = true, entities = 42},
            nether = {loaded = false, entities = 0}
        }
    },
    settings = {
        graphics = "high",
        sound = true,
        controls = {
            forward = "W",
            backward = "S",
            left = "A",
            right = "D",
            jump = "Space"
        }
    },
    timestamp = time.unix()
}

-- Convert to JSON string
local json_string = json.stringify(game_state)

-- Save to file
fs.write_to_file("game_state.json", json_string)
engine.log("Game state saved to JSON file", 0, 255, 0, 255)

-- Later, load the saved state
if fs.does_file_exist("game_state.json") then
    local saved_json = fs.read_from_file("game_state.json")
    local saved_state = json.parse(saved_json)
    
    engine.log("Loaded game state for player: " .. saved_state.player.name, 255, 255, 255, 255)
    engine.log("Player position: (" .. 
        saved_state.player.position.x .. ", " .. 
        saved_state.player.position.y .. ", " .. 
        saved_state.player.position.z .. ")", 255, 255, 255, 255)
    engine.log("Player has " .. #saved_state.player.inventory .. " items", 255, 255, 255, 255)
end

Last updated

Was this helpful?