Sample code for 30+ languages & platforms
Zig

Build JSON with Mixture of Arrays and Objects

See more JSON Examples

Another example showing how to build JSON containing a mixture of arrays and objects.

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();

    // We want to build the following JSON:

    // {
    //   "accountEnabled": true,
    //   "assignedLicenses": [
    //     {
    //       "disabledPlans": [ "bea13e0c-3828-4daa-a392-28af7ff61a0f" ],
    //       "skuId": "skuId-value"
    //     }
    //   ],
    //   "assignedPlans": [
    //     {
    //       "assignedDateTime": "datetime-value",
    //       "capabilityStatus": "capabilityStatus-value",
    //       "service": "service-value",
    //       "servicePlanId": "bea13e0c-3828-4daa-a392-28af7ff61a0f"
    //     }
    //   ],
    //   "businessPhones": [
    //     "businessPhones-value"
    //   ],
    //   "city": "city-value",
    //   "companyName": "companyName-value"
    // }

    const json = try chilkat.JsonObject.init();
    defer json.deinit();
    json.updateBool("accountEnabled", true) catch {};
    json.setI(0);
    json.updateString("assignedLicenses[i].disabledPlans[0]", "bea13e0c-3828-4daa-a392-28af7ff61a0f") catch {};
    json.updateString("assignedLicenses[i].skuId", "skuId-value") catch {};
    json.updateString("assignedPlans[i].assignedDateTime", "datetime-value") catch {};
    json.updateString("assignedPlans[i].capabilityStatus", "capabilityStatus-value") catch {};
    json.updateString("assignedPlans[i].service", "service-value") catch {};
    json.updateString("assignedPlans[i].servicePlanId", "bea13e0c-3828-4daa-a392-28af7ff61a0f") catch {};
    json.updateString("businessPhones[i]", "businessPhones-value") catch {};
    json.updateString("city", "city-value") catch {};
    json.updateString("companyName", "companyName-value") catch {};

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

    // Output:

    // {
    //   "accountEnabled": true,
    //   "assignedLicenses": [
    //     {
    //       "disabledPlans": [
    //         "bea13e0c-3828-4daa-a392-28af7ff61a0f"
    //       ],
    //       "skuId": "skuId-value"
    //     }
    //   ],
    //   "assignedPlans": [
    //     {
    //       "assignedDateTime": "datetime-value",
    //       "capabilityStatus": "capabilityStatus-value",
    //       "service": "service-value",
    //       "servicePlanId": "bea13e0c-3828-4daa-a392-28af7ff61a0f"
    //     }
    //   ],
    //   "businessPhones": [
    //     "businessPhones-value"
    //   ],
    //   "city": "city-value",
    //   "companyName": "companyName-value"
    // }
}