jsnprintf()

Write JSON data to a character array, up to a given number of characters

Synopsis:

#include <sys/json.h>
int jsnprintf(char *buffer,
              int len,
              const char *format,
              ...);

Arguments:

buffer
A pointer to a buffer to store the formatted string.
len
The maximum number of characters to store in the buffer, including a terminating null character. If this value is at least one, the buffer will be null-terminated.
format
A string that specifies the format of the output. This string determines what additional arguments you need to provide.

Library:

libjson

Description:

The jsnprintf() function formats JSON data based on the format string and stores the result in buffer. The maximum number of characters written, including a terminating null character, is given by len.

The format-specifier string must be valid JSON with the following exceptions:
  • String, Boolean, and numeric values can be formatted using additional arguments following the string, much like printf(). Conversion specifiers are similar to printf() with the following differences:
    • Field width is not supported.
    • The only type length specifier supported is ll (double "el") to indicate a long long or unsigned long long.
    • The printf() conversion type specifiers supported are 'd', 'i', 'e', 'E', 'f', 'F', 'g', 'G', 's' and 'u'.
    • A 'b' conversion type specifier can be used to indicate that an int argument should be formatted as a Boolean value.
    • A 'j' conversion type specifier can be used to indicate that a string argument contains either a single pre-formatted JSON-like value or a comma-separated list of JSON-like values. The rules for what constitutes a JSON-like value depend on the context in which it is used. If used within an object, for example { %j, %j }, the JSON-like value or each JSON-like value in a list must be in the form "name":value when value is a JSON value. When used outside of an object, each value or value in a list must be valid JSON.
  • Property names can be specified as '%s' in which case the name is taken from the next function argument.
  • Property names can be contained within the format-specifier string without being enclosed in double quotes; the output string will have the double quotes inserted.

When an error is detected within the format-specifier string that leads to an invalid JSON output string, a question mark will be inserted into the output string and the function will return -1. Not all errors are detected.

Returns:

The number of characters that were written to the output buffer or that would have been written had it been large enough, not including the terminating null character. -1 is returned if the format-specifier string is invalid.