Sample code for 30+ languages & platforms
Swift

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 Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    // This example assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    let http = CkoHttp()!

    // Get the JSON we'll be parsing..
    var jsonStr: String? = http.quickGetStr(url: "https://www.chilkatsoft.com/exampleData/qb_customer_balance_detail_report_2.json")
    if http.lastMethodSuccess != true {
        print("\(http.lastErrorText!)")
        return
    }

    let json = CkoJsonObject()!
    json.load(json: jsonStr)

    // 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.
    let csv = CkoCsv()!
    csv.hasColumnNames = true

    // Set the column names of the CSV.
    var numColumns: Int = json.size(ofArray: "Columns.Column").intValue
    if numColumns < 0 {
        print("Unable to get column names")
        return
    }

    var i: Int = 0
    while i < numColumns {
        json.i = i
        csv.setColumnName(index: i, columnName: json.string(of: "Columns.Column[i].ColTitle"))
        i = i + 1
    }

    // Let's get the rows.
    // We'll ignore the Header and Summary, and just get the data.
    var row: Int = 0
    var numRows: Int = json.size(ofArray: "Rows.Row[0].Rows.Row").intValue
    if numRows < 0 {
        print("Unable to get data rows")
        return
    }

    while row < numRows {
        json.i = row
        numColumns = json.size(ofArray: "Rows.Row[0].Rows.Row[i].ColData").intValue
        var col: Int = 0
        while col < numColumns {
            json.j = col
            csv.setCell(row: row, col: col, content: json.string(of: "Rows.Row[0].Rows.Row[i].ColData[j].value"))
            col = col + 1
        }

        row = row + 1
    }

    // Show the CSV 
    print("\(csv.saveToString()!)")

    // Save to a CSV file
    success = csv.saveFile(path: "qa_output/customerDetailReport.csv")

}