KCGIJSON(3) Library Functions Manual KCGIJSON(3)

kcgijsonJSON output for kcgi

library “libkcgijson”

#include <sys/types.h>
#include <stdarg.h>
#include <stdint.h>
#include <kcgi.h>
#include <kcgijson.h>

Produce output of JSON objects and arrays in a kcgi(3) context allocated with khttp_parse(3).

To compile and link, use pkg-config(1) as follows:

% cc `pkg-config --cflags kcgi-json` -c sample.c
% cc -o sample sample.o `pkg-config --libs kcgi-json`

All kcgijson functions accept a struct kjsonreq object. To use this properly, open a context with kjson_open(3), add content, then end with kjson_close(3).

Let struct kreq *r already be initialised, and the request be for KMIME_APP_JSON. The following fragment prints out a simple JSON object. Error checking is omitted for brevity.

kjson_open(&req, r);
kcgi_writer_disable(r);
khttp_head(r, kresps[KRESP_STATUS],
  "%s", khttps[KHTTP_200]);
khttp_head(r, kresps[KRESP_CONTENT_TYPE],
  "%s", kmimetypes[KMIME_APP_JSON]);
khttp_body(r);
kjson_open(&req);
kjson_objp_open(&req, "anobj");
kjson_putstringp(&req, "astring", "baz");
kjson_putintp(&req, "anint", 12345);
kjson_stringp_open(&req, "alongstring");
kjson_string_puts(&req, "hello, ");
kjson_string_puts(&req, "world.");
kjson_string_close(&req); /* alongstring */
kjson_arrayp_open(&req, "anarray");
kjson_putint(&req, 1);
kjson_putint(&req, 2);
kjson_putdouble(&req, 3.0);
kjson_array_close(&req); /* anarray */
kjson_obj_close(&req); /* anobj */
kjson_close(&req);

Following the kcgi_writer_disable(3) call, no further writers may be allocated.

kjson_array_close(3), kjson_array_open(3), kjson_close(3), kjson_obj_close(3), kjson_obj_open(3), kjson_open(3), kjson_putbool(3), kjson_putdouble(3), kjson_putint(3), kjson_putnull(3), kjson_putstring(3), kjson_string_close(3), kjson_string_open(3), kjson_string_write(3)

The kcgijson functions conform to the ECMA-404 JSON Data Interchange Standard, also documented as RFC 7159. Parts of this document reference ECMAScript 5, commonly known as JavaScript.

Written by Kristaps Dzonsons <kristaps@bsd.lv>.

March 27, 2020 OpenBSD 6.7