Sample code for 30+ languages & platforms
Zig

Google Sheets - Read a Single Range

See more Google Sheets Examples

Reads the values stored in the range Sheet1!A1:B5 and returns them in the response.

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 example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // This example uses a previously obtained access token having permission for the
    // Google Sheets scope.

    // In this example, Get Google Sheets OAuth2 Access Token, the access
    // token was saved to a JSON file.  This example fetches the access token from the file..
    const json_token = try chilkat.JsonObject.init();
    defer json_token.deinit();
    try json_token.loadFile("qa_data/tokens/googleSheets.json");
    if (!json_token.hasMember("access_token")) {
        std.debug.print("No access token found.\n", .{});
        return;
    }

    const http = try chilkat.Http.init();
    defer http.deinit();
    http.setAuthToken(try json_token.stringOf(alloc, "access_token"));
    http.setSessionLogFilename("qa_output/sessionLog.txt");

    // Get the cells defined by the range A1:B5
    const json_response = http.quickGetStr(alloc, "https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId/values/Sheet1!A1:B5") catch {
        std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("{s}\n", .{json_response});

    const json = try chilkat.JsonObject.init();
    defer json.deinit();
    json.load(json_response) catch {};

    // A sample response is shown below.
    // To generate the parsing source code for a JSON response, paste
    // the JSON into this online tool: Generate JSON parsing code

    // {
    //   "range": "Sheet1!A1:B5",
    //   "majorDimension": "ROWS",
    //   "values": [
    //     [
    //       "Item",
    //       "Cost"
    //     ],
    //     [
    //       "Wheel",
    //       "$20.50"
    //     ],
    //     [
    //       "Door",
    //       "$15"
    //     ],
    //     [
    //       "Engine",
    //       "$100"
    //     ],
    //     [
    //       "Totals",
    //       "$135.50"
    //     ]
    //   ]
    // }

    var i: i32 = 0;
    var j: i32 = 0;
    var count_j: i32 = 0;

    _ = try json.stringOf(alloc, "range");
    _ = try json.stringOf(alloc, "majorDimension");
    i = 0;
    const count_i = json.sizeOfArray("values");
    while (i < count_i) {
        json.setI(i);
        j = 0;
        count_j = json.sizeOfArray("values[i]");
        while (j < count_j) {
            json.setJ(j);
            _ = try json.stringOf(alloc, "values[i][j]");
            j = j + 1;
        }

        i = i + 1;
    }
}