Sample code for 30+ languages & platforms
Zig Requires Chilkat v11.4.0+

Call a JavaScript Function Returning an Object

See more JavaScript Examples

Demonstrates how to call a JavaScript function that returns an object.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // This is the JavaScript function we'll call:

    // function getSettings() {
    //     return {
    //         theme: "dark",
    //         notifications: true,
    //         version: 1.0
    //     };
    // }

    const sb_script = try chilkat.StringBuilder.init();
    defer sb_script.deinit();
    sb_script.append("function getSettings() {") catch {};
    sb_script.append("    return {") catch {};
    sb_script.append("        theme: \"dark\",") catch {};
    sb_script.append("        notifications: true,") catch {};
    sb_script.append("        version: 1.0") catch {};
    sb_script.append("    };") catch {};
    sb_script.append("}") catch {};

    const js = try chilkat.Js.init();
    defer js.deinit();

    const result = try chilkat.JsonObject.init();
    defer result.deinit();
    result.setEmitCompact(false);

    // Call Eval to add the function to the context's global object
    js.eval(sb_script, result) catch {
        // Examine the result for an exception.
        std.debug.print("{s}\n", .{try result.emit(alloc)});

        // Also examine the LastErrorText.
        std.debug.print("{s}\n", .{try js.getLastErrorText(alloc)});
        return;
    };

    // ------------------------------------------------------------------------------
    // Call the function getSettings()

    const func_call = try chilkat.JsonObject.init();
    defer func_call.deinit();

    // Create JSON specifying the function name and arguments
    // The function has no arguments, so we only specify the name.

    // {
    //   "name": "getSettings",
    // }

    func_call.updateString("name", "getSettings") catch {};

    js.callFunction(func_call, result) catch {
        // Examine the result for an exception.
        std.debug.print("{s}\n", .{try result.emit(alloc)});

        // Also examine the LastErrorText.
        std.debug.print("{s}\n", .{try js.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("{s}\n", .{try result.emit(alloc)});

    // Output:
    // {
    //   "type": "object",
    //   "value": {
    //     "theme": "dark",
    //     "notifications": true,
    //     "version": 1
    //   }
    // }

    // Examine the object's members
    std.debug.print("theme: {s}\n", .{try result.stringOf(alloc, "value.theme")});
    std.debug.print("notifications: {}\n", .{result.boolOf("value.notifications")});
    std.debug.print("version: {d}\n", .{result.intOf("value.version")});

    // Output:
    // theme: dark
    // notifications: True
    // version: 1
}