diff options
author | Maxim Anisimov <maxim.anisimov.ua@gmail.com> | 2020-06-05 09:29:23 +0300 |
---|---|---|
committer | Aleksander Morgado <aleksander@aleksander.es> | 2020-06-05 07:34:54 +0000 |
commit | 62c6f941a2ea44b0f67fbb849c92335d78137b96 (patch) | |
tree | fa762867b0113295c1d2cba4f0b3c91d1664c54e | |
parent | 1e0b38d98aff792481f4635c524bbf669b0be5ad (diff) |
cli: make control chars in strings are escaped correctly for json output
We need to change json output escaping according to this
https://bugzilla.gnome.org/show_bug.cgi?id=730425
Signed-off-by: Maxim Anisimov <maxim.anisimov.ua@gmail.com>
-rw-r--r-- | cli/mmcli-output.c | 47 |
1 files changed, 45 insertions, 2 deletions
diff --git a/cli/mmcli-output.c b/cli/mmcli-output.c index 6799ab6d..1265856d 100644 --- a/cli/mmcli-output.c +++ b/cli/mmcli-output.c @@ -1087,6 +1087,49 @@ dump_output_list_keyvalue (MmcF field) /******************************************************************************/ /* JSON-friendly output */ +static gchar * +json_strescape (const gchar *str) +{ + const gchar *p; + const gchar *end; + GString *output; + gsize len; + + len = strlen (str); + end = str + len; + output = g_string_sized_new (len); + + for (p = str; p < end; p++) { + if (*p == '\\' || *p == '"') { + g_string_append_c (output, '\\'); + g_string_append_c (output, *p); + } else if ((*p > 0 && *p < 0x1f) || *p == 0x7f) { + switch (*p) { + case '\b': + g_string_append (output, "\\b"); + break; + case '\f': + g_string_append (output, "\\f"); + break; + case '\n': + g_string_append (output, "\\n"); + break; + case '\r': + g_string_append (output, "\\r"); + break; + case '\t': + g_string_append (output, "\\t"); + break; + default: + g_string_append_printf (output, "\\u00%02x", (guint)*p); + break; + } + } else + g_string_append_c (output, *p); + } + return g_string_free (output, FALSE); +} + static gint list_sort_by_keys (const OutputItem *item_a, const OutputItem *item_b) @@ -1146,7 +1189,7 @@ dump_output_json (void) gchar *escaped = NULL; if (single->value) - escaped = g_strescape (single->value, "\v"); + escaped = json_strescape (single->value); g_print ("\"%s\":\"%s\"", current_path[cur_dlen], escaped ? escaped : "--"); g_free (escaped); @@ -1160,7 +1203,7 @@ dump_output_json (void) for (i = 0; i < n; i++) { gchar *escaped; - escaped = g_strescape (multiple->values[i], "\v"); + escaped = json_strescape (multiple->values[i]); g_print("\"%s\"", escaped); if (i < n - 1) g_print(","); |