commit 964521a330be508698b7d199cc6f1ce8e0847b41
parent 05c2948cdca89ddec3bd6e275e705d0d758ffc2c
Author: Shek Muktar <im.skm07@gmail.com>
Date: Tue, 29 Apr 2025 21:44:21 +0200
json: Added improvements when building a string.
Previously when a string contains '"' (double quote) then the kore
json was not escaping it that causes JSON parser client to throw error
example JavaScript's JSON.parse() function.
Signed-off-by: Joris Vink <joris@sanctorum.se>
Diffstat:
src/json.c | | | 56 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++- |
1 file changed, 55 insertions(+), 1 deletion(-)
diff --git a/src/json.c b/src/json.c
@@ -33,6 +33,7 @@ static int json_consume_whitespace(struct kore_json *);
static int json_next_byte(struct kore_json *, u_int8_t *, int);
static char *json_get_string(struct kore_json *);
+static void json_build_string(struct kore_json_item *, const char *);
static int json_parse_array(struct kore_json *, struct kore_json_item *);
static int json_parse_object(struct kore_json *, struct kore_json_item *);
@@ -191,7 +192,7 @@ kore_json_create_item(struct kore_json_item *parent, const char *name,
break;
case KORE_JSON_TYPE_STRING:
p = va_arg(args, const char *);
- item->data.string = kore_strdup(p);
+ json_build_string(item, p);
break;
case KORE_JSON_TYPE_NUMBER:
item->data.number = va_arg(args, double);
@@ -958,3 +959,56 @@ cleanup:
return (res);
}
+
+static void
+json_build_string(struct kore_json_item *item, const char *string)
+{
+ char ch;
+ char *res;
+ struct kore_buf tmpbuf;
+
+ kore_buf_init(&tmpbuf, 512);
+
+ res = NULL;
+ while (*string) {
+ ch = *string;
+ switch (ch) {
+ case '\"':
+ case '\\':
+ case '/':
+ kore_buf_append(&tmpbuf, "\\", sizeof(u_int8_t));
+ break;
+ case '\b':
+ kore_buf_append(&tmpbuf, "\\", sizeof(u_int8_t));
+ ch = 'b';
+ break;
+ case '\f':
+ kore_buf_append(&tmpbuf, "\\", sizeof(u_int8_t));
+ ch = 'f';
+ break;
+ case '\n':
+ kore_buf_append(&tmpbuf, "\\", sizeof(u_int8_t));
+ ch = 'n';
+ break;
+ case '\r':
+ kore_buf_append(&tmpbuf, "\\", sizeof(u_int8_t));
+ ch = 'r';
+ break;
+ case '\t':
+ kore_buf_append(&tmpbuf, "\\", sizeof(u_int8_t));
+ ch = 't';
+ break;
+ default:
+ /* normal */
+ break;
+ }
+
+ kore_buf_append(&tmpbuf, &ch, sizeof(ch));
+ ++string;
+ }
+
+ res = kore_buf_stringify(&tmpbuf, NULL);
+ item->data.string = kore_strdup(res);
+
+ kore_buf_cleanup(&tmpbuf);
+}