Sample code for 30+ languages & platforms
Zig

Read/Write JSON with Binary Data such as JPEG Files

See more JSON Examples

Demonstrates how binary files could be stored in JSON in base64 format. Creates JSON containing the contents of a JPG file, and then reads the JSON to extract the JPEG image.

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

    // First load a small JPG file..
    const bd = try chilkat.BinData.init();
    defer bd.deinit();

    try bd.loadFile("qa_data/jpg/starfish20.jpg");
    // Assume success, but your code should check for success..

    // Create JSON containing the binary data in base64 format.
    const json1 = try chilkat.JsonObject.init();
    defer json1.deinit();
    json1.updateBd("starfish", "base64", bd) catch {};

    const json_str = try json1.emit(alloc);
    std.debug.print("{s}\n", .{json_str});

    // Here's the output:
    // {"starfish":"/9j/4AAQSkZJRgA ... cN2iuLFsCEbDGxQkI6RO/n//2Q=="}

    // Let's create a new JSON object, load it with the above JSON, and extract the JPG image..
    const json2 = try chilkat.JsonObject.init();
    defer json2.deinit();
    json2.load(json_str) catch {};

    // Get the binary bytes.
    const bd2 = try chilkat.BinData.init();
    defer bd2.deinit();
    json2.bytesOf("starfish", "base64", bd2) catch {};

    // Save to a file.
    try bd2.writeFile("qa_output/starfish20.jpg");

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