]> xenbits.xensource.com Git - libvirt.git/commitdiff
util: json: introduce virJSONStringPrettifyBlanks
authorJán Tomko <jtomko@redhat.com>
Thu, 15 Feb 2024 15:21:23 +0000 (16:21 +0100)
committerJán Tomko <jtomko@redhat.com>
Tue, 24 Sep 2024 06:24:00 +0000 (08:24 +0200)
A horribly named function for unifying formatting when pretty-printing
empty JSON arrays and objects. Useful for having stable test output
even if different JSON libraries format these differently.

Signed-off-by: Ján Tomko <jtomko@redhat.com>
Reviewed-by: Peter Krempa <pkrempa@redhat.com>
src/libvirt_private.syms
src/util/virjson.c
src/util/virjson.h

index f15d16c2921d12362ba53c371555098f0b4fc380..02dacea857dc250faee978c85fb7d169cab4f5ad 100644 (file)
@@ -2613,6 +2613,7 @@ virISCSIScanTargets;
 
 
 # util/virjson.h
+virJSONStringPrettifyBlanks;
 virJSONStringReformat;
 virJSONValueArrayAppend;
 virJSONValueArrayAppendString;
index 57707350dad8da96a7532bcff6463d862495b0bc..0edf86cd1c4e4988763856c7be31ee44b8a054dd 100644 (file)
@@ -1861,6 +1861,40 @@ virJSONStringReformat(const char *jsonstr,
     return virJSONValueToString(json, pretty);
 }
 
+/**
+ * virJSONStringPrettifyBlanks:
+ * @jsonstr: string to prettify
+ *
+ * In the pretty mode of printing, various versions of JSON libraries
+ * format empty arrays and objects differently.
+ *
+ * Unify this to "[]" and "{}" which are used by json-c 0.17 and newer.
+ * https://github.com/json-c/json-c/issues/778
+ *
+ * This format is also used by Python's 'json.dump' method.
+ *
+ * Returns the reformatted JSON string on success.
+ */
+char *virJSONStringPrettifyBlanks(const char *jsonstr)
+{
+    virBuffer buf = VIR_BUFFER_INITIALIZER;
+    const char *p;
+
+    for (p = jsonstr; *p && p[1]; p++) {
+        virBufferAddChar(&buf, *p);
+
+        if ((p[0] == '{' || p[0] == '[') && p[1] == '\n') {
+            const char *q = p + 1;
+
+            virSkipSpaces(&q);
+
+            if (*q == '}' || *q == ']')
+                p = q - 1;
+        }
+    }
+
+    return virBufferContentAndReset(&buf);
+}
 
 static virJSONValue *
 virJSONValueObjectDeflattenKeys(virJSONValue *json);
index e622798fe7eb2a163587727d6772b6cb8acdfbc0..d8481e58909692ebaf174ec91b3361a1d4da3dce 100644 (file)
@@ -271,6 +271,8 @@ virJSONValueCopy(const virJSONValue *in);
 char *
 virJSONStringReformat(const char *jsonstr,
                       bool pretty);
+char *
+virJSONStringPrettifyBlanks(const char *jsonstr);
 
 virJSONValue *
 virJSONValueObjectDeflatten(virJSONValue *json);