Sample code for 30+ languages & platforms
Zig

QuickBooks - Parse the JSON of a Customer Balance Detail Report

See more CSV Examples

This example is to show how to parse the JSON of a particular Quickbooks report. The techniques shown here may help in parsing similar reports.

The JSON to be parsed is available at Sample Quickbooks Customer Balance Detail Report JSON

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

    const http = try chilkat.Http.init();
    defer http.deinit();

    // Get the JSON we'll be parsing..
    const json_str = http.quickGetStr(alloc, "https://www.chilkatsoft.com/exampleData/qb_customer_balance_detail_report_2.json") catch {
        std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
        return;
    };

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

    // As an alternative to manually writing code, use this online tool to generate parsing code from sample JSON:
    // Generate Parsing Code from JSON

    // Let's parse the JSON into a CSV, and then save to a CSV file.
    const csv = try chilkat.Csv.init();
    defer csv.deinit();
    csv.setHasColumnNames(true);

    // Set the column names of the CSV.
    var num_columns: i32 = json.sizeOfArray("Columns.Column");
    if (num_columns < 0) {
        std.debug.print("Unable to get column names\n", .{});
        return;
    }

    var i: i32 = 0;
    while (i < num_columns) {
        json.setI(i);
        csv.setColumnName(i, try json.stringOf(alloc, "Columns.Column[i].ColTitle")) catch {};
        i = i + 1;
    }

    // Let's get the rows.
    // We'll ignore the Header and Summary, and just get the data.
    var row: i32 = 0;
    const num_rows = json.sizeOfArray("Rows.Row[0].Rows.Row");
    if (num_rows < 0) {
        std.debug.print("Unable to get data rows\n", .{});
        return;
    }

    while (row < num_rows) {
        json.setI(row);
        num_columns = json.sizeOfArray("Rows.Row[0].Rows.Row[i].ColData");
        var col: i32 = 0;
        while (col < num_columns) {
            json.setJ(col);
            csv.setCell(row, col, try json.stringOf(alloc, "Rows.Row[0].Rows.Row[i].ColData[j].value")) catch {};
            col = col + 1;
        }

        row = row + 1;
    }

    // Show the CSV
    std.debug.print("{s}\n", .{try csv.saveToString(alloc)});

    // Save to a CSV file
    try csv.saveFile("qa_output/customerDetailReport.csv");
}