util: json: introduce virJSONStringPrettifyBlanks

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>
This commit is contained in:
Ján Tomko 2024-02-15 16:21:23 +01:00
parent e14a5fcac4
commit 330cf7f492
3 changed files with 37 additions and 0 deletions

View File

@ -2613,6 +2613,7 @@ virISCSIScanTargets;
# util/virjson.h # util/virjson.h
virJSONStringPrettifyBlanks;
virJSONStringReformat; virJSONStringReformat;
virJSONValueArrayAppend; virJSONValueArrayAppend;
virJSONValueArrayAppendString; virJSONValueArrayAppendString;

View File

@ -1861,6 +1861,40 @@ virJSONStringReformat(const char *jsonstr,
return virJSONValueToString(json, pretty); 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 * static virJSONValue *
virJSONValueObjectDeflattenKeys(virJSONValue *json); virJSONValueObjectDeflattenKeys(virJSONValue *json);

View File

@ -271,6 +271,8 @@ virJSONValueCopy(const virJSONValue *in);
char * char *
virJSONStringReformat(const char *jsonstr, virJSONStringReformat(const char *jsonstr,
bool pretty); bool pretty);
char *
virJSONStringPrettifyBlanks(const char *jsonstr);
virJSONValue * virJSONValue *
virJSONValueObjectDeflatten(virJSONValue *json); virJSONValueObjectDeflatten(virJSONValue *json);