Skip to content

Commit b93853a

Browse files
committed
util: add json_object_add_format() function
This is to add a format string into the json object. Signed-off-by: Tokunori Ikegami <[email protected]>
1 parent 271d198 commit b93853a

2 files changed

Lines changed: 17 additions & 0 deletions

File tree

util/json.c

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// SPDX-License-Identifier: GPL-2.0-or-later
22
#include <stdio.h>
33
#include <errno.h>
4+
#include <stdarg.h>
45

56
#include "json.h"
67
#include "types.h"
@@ -135,3 +136,18 @@ void json_object_add_0nprix64(struct json_object *o, const char *k, uint64_t v,
135136
sprintf(str, "0x%0*"PRIx64"", width, v);
136137
json_object_add_value_string(o, k, str);
137138
}
139+
140+
void json_object_add_format(struct json_object *o, const char *k, const char *format, ...)
141+
{
142+
_cleanup_free_ char *value = NULL;
143+
va_list ap;
144+
145+
va_start(ap, format);
146+
147+
if (vasprintf(&value, format, ap) < 0)
148+
value = NULL;
149+
150+
json_object_add_value_string(o, k, value ? value : "Could not allocate string");
151+
152+
va_end(ap);
153+
}

util/json.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,5 +78,6 @@ void json_object_add_byte_array(struct json_object *o, const char *k, unsigned c
7878
void json_object_add_nprix64(struct json_object *o, const char *k, uint64_t v);
7979
void json_object_add_uint_0nx(struct json_object *o, const char *k, __u32 v, int width);
8080
void json_object_add_0nprix64(struct json_object *o, const char *k, uint64_t v, int width);
81+
void json_object_add_format(struct json_object *o, const char *k, const char *format, ...);
8182

8283
#endif /* __JSON__H */

0 commit comments

Comments
 (0)