json_fmt.h
posts c json macros programmingAs an alternative to writing JSON by hand using purely printf, I written a helper header file called json_fmt.h
.
There are other options, but I just want something quick to get going with json output, so written a series of
C macros that I can use to make it easier to write the formatting string for a printf call.
Note that this approach is quite limited to future expansion, but is suitable for quickly getting a json output without including other dependencies as this is only a single header file.
But it would be helpful for people who stumble on this post to checkout these repos that I personally would recommend checking out for C code embedded system purpose. Just note that both options do use the heap while my approach does not. This might be a factor in choosing mine or the options below.
- cJSON - Ultralightweight JSON parser in ANSI C
- I used before and quite enjoyed using.
- Uses Malloc
- frozen - JSON parser and generator for C/C++ with scanf/printf like interface.
- Just discovered recently and I like the idea of being able to use printf style semantics
- Uses Malloc
But if the above is too overkill or you don't got the time and mindspace to deal with integrating it in... or you want to minimize dependencies. That's when you can consider below.
The design rule for this micro library is to only deal with the most common json elements that is
error prone or annoying to manually write. So in this context, it would tend to be dealing with "
and keeping track of the keys and values. So ultimately instead of writing
printf("{\"user\":%s, \"age\":%d)}", "marcus", 25);
You would write:
printf("{" JSON_FMT_STR("user") ", " JSON_FMT_INT("age") "}", "marcus", 25)
You still need to manually write the values to the left side, but at least you can more easily
keep mental note of all the types when reading the manually written json strings. As well as
being sure that you have not forgotten to escape "
or :
somewhere.
- Pros: Much less error prone than writing json purely by hand
- Cons: Still more error prone than using an actual json library like cJSON
To use this micro library, just copy these code below into a file named json_fmt.h
.
/*
json_fmt.h (2025-01-26)
A C Micro Formatting Library for manually writing json strings using printf
e.g. printf("{"JSON_FMT_STR("user")", "JSON_FMT_INT("age")"}", "marcus", 25)
# MIT License
Copyright (c) 2025 Brian Khuu
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef JSON_FMT_H
#define JSON_FMT_H
#define JSON_FMT_KEY(KEY) "\"" KEY "\""
#define JSON_FMT(KEY, FMT) JSON_FMT_KEY(KEY) ":" FMT
#define JSON_FMT_STR(KEY) JSON_FMT(KEY, "\"%s\"")
#define JSON_FMT_INT(KEY) JSON_FMT(KEY, "%d")
#define JSON_FMT_FLT(KEY) JSON_FMT(KEY, "%lf")
#define JSON_FMT_VAL(KEY) JSON_FMT(KEY, "%s")
#define JSON_VAL_TRUE "true"
#define JSON_VAL_FALSE "false"
#define JSON_VAL_NULL "null"
#define JSON_VAL_STR(VAL) "\"" VAL "\"" ///< Note that VAL must be json escaped
#define JSON_VAL_BOOL(VAL) (VAL ? JSON_VAL_TRUE : JSON_VAL_FALSE)
static inline char *json_fmt_escaped_string(char *buffer, const unsigned long buffer_size, const char *str)
{
// This escapes string for safe inclusion in json string (Ref: https://www.json.org/img/string.png)
char esc_char[] = {'\"', '\\', '/', '\b', '\f', '\n', '\r', '\t'};
char alt_char[] = {'"', '\\', '/', 'b', 'f', 'n', 'r', 't'};
int char_count = 0;
for (; *str && (char_count < buffer_size - 3); str++)
{
const char ch = *str;
for (int i = 0; i < (sizeof(esc_char) / sizeof(esc_char[0])); i++)
{
if (ch == esc_char[i])
{
buffer[char_count++] = '\\';
buffer[char_count++] = alt_char[i];
goto escaped_character_applied;
}
}
buffer[char_count++] = ch;
escaped_character_applied:
continue;
}
buffer[char_count] = '\0';
return buffer;
}
#endif
For example of how you can use this in your project, have a look at this example json_fmt_demo.c
#include <stdio.h>
#include "json_fmt.h"
int main()
{
char buffer[200];
printf("Escaped String 1: \"%s\"\n", json_fmt_escaped_string(buffer, sizeof(buffer), "Hello \"World\"!"));
printf("Escaped String 2: \"%s\"\n", json_fmt_escaped_string(buffer, sizeof(buffer), "This is a line\n And a newline\n\tplus tabs"));
printf("Escaped String 3: \"%s\"\n", json_fmt_escaped_string(buffer, sizeof(buffer), "Backslash \\ and forward slash /"));
printf("Formatted JSON (String): {" JSON_FMT_STR("name") "}\n", "Alice");
printf("Formatted JSON (Integer): {" JSON_FMT_INT("age") "}\n", 30);
printf("Formatted JSON (Float): {" JSON_FMT_FLT("height") "}\n", 5.9);
printf("Formatted JSON (Bool=true): {" JSON_FMT_VAL("ready") "}\n", JSON_VAL_BOOL(1));
printf("Formatted JSON (Bool=false): {" JSON_FMT_VAL("ready") "}\n", JSON_VAL_BOOL(0));
printf("Formatted JSON (null): {" JSON_FMT_VAL("ready") "}\n", JSON_VAL_NULL);
printf("Combined JSON: {" JSON_FMT_STR("user") ", " JSON_FMT_INT("age") "}\n", "marcus", 25);
return 0;
}
When compiled using tcc -run json_fmt_demo.c
you will get this output:
Escaped String 1: "Hello \"World\"!"
Escaped String 2: "This is a line\n And a newline\n\tplus tabs"
Escaped String 3: "Backslash \\ and forward slash \/"
Formatted JSON (String): {"name":"Alice"}
Formatted JSON (Integer): {"age":30}
Formatted JSON (Float): {"height":5.900000}
Formatted JSON (Bool=true): {"ready":true}
Formatted JSON (Bool=false): {"ready":false}
Formatted JSON (null): {"ready":null}
Combined JSON: {"user":"marcus", "age":25}
Key thing to note, is that I've also included a small function named json_fmt_escaped_string()
.
This is because while you can manually and easily sanitize integers and floats. It's much harder
to manually sanitize each string.
Just note that you will need to have a separate buffer for each call to json_fmt_escaped_string() to the same printf. An example which illustrate this point is shown below
#include <stdio.h>
#include "json_fmt.h"
int main() {
char buffer1[200];
char buffer2[200];
printf("Double Escaped String (Incorrect Usage): [ \"%s\", \"%s\" ]\n",
json_fmt_escaped_string(buffer1, sizeof(buffer1), "Bye \"World\"!"),
json_fmt_escaped_string(buffer1, sizeof(buffer1), "Hello \"World\"!"));
printf("Double Escaped String (Correct Usage): [ \"%s\", \"%s\" ]\n",
json_fmt_escaped_string(buffer1, sizeof(buffer1), "Bye \"World\"!"),
json_fmt_escaped_string(buffer2, sizeof(buffer2), "Hello \"World\"!"));
return 0;
}
Which will output this result:
Double Escaped String (Incorrect Usage): [ "Hello \"World\"!", "Hello \"World\"!" ]
Double Escaped String (Correct Usage): [ "Bye \"World\"!", "Hello \"World\"!" ]
Anyway hope this will be useful for you! Especially if you have a deadline! Just remember to revisit and update your code to use a proper json library when you get the time and space to do so!