From cbfc823097c070e3be10af797e09419afea57f16 Mon Sep 17 00:00:00 2001 From: Hendrik Schreiber Date: Wed, 21 Oct 2020 14:42:00 +0200 Subject: [PATCH] Allow to change the default indentation of the produced JSON. The default is 2, which can lead to fairly large bloat, when considering ten-thousands of JAMS (think global tempo estimates like https://github.com/tempoeval/tempo_eval/tree/main/annotations). Of course one can go the gzip/jamz route, which will create smaller files, but at the price of (easy/casual) editability. Being able to simple pass indent=None is a compromise. It still allows manual editing, while also reducing size quite a bit. --- jams/core.py | 12 ++++++++++-- tests/test_jams.py | 5 +++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/jams/core.py b/jams/core.py index 2f0160ee..6b7ec3a3 100644 --- a/jams/core.py +++ b/jams/core.py @@ -1741,7 +1741,7 @@ def search(self, **kwargs): return self.annotations.search(**kwargs) - def save(self, path_or_file, strict=True, fmt='auto'): + def save(self, path_or_file, strict=True, fmt='auto', indent=2): """Serialize annotation as a JSON formatted stream to file. Parameters @@ -1762,6 +1762,14 @@ def save(self, path_or_file, strict=True, fmt='auto'): If the input is an open file handle, `jams` encoding is used. + indent : int + If a non-negative integer, then JSON array elements and + object members will be pretty-printed with that indent level. An indent + level of 0 will only insert newlines. `None` is the most compact + representation. + + By default, 2 is used. + Raises ------ @@ -1777,7 +1785,7 @@ def save(self, path_or_file, strict=True, fmt='auto'): self.validate(strict=strict) with _open(path_or_file, mode='w', fmt=fmt) as fdesc: - json.dump(self.__json__, fdesc, indent=2) + json.dump(self.__json__, fdesc, indent=indent) def validate(self, strict=True): '''Validate a JAMS object against the schema. diff --git a/tests/test_jams.py b/tests/test_jams.py index 3f952c82..33523b9e 100644 --- a/tests/test_jams.py +++ b/tests/test_jams.py @@ -444,9 +444,10 @@ def input_jam(): return jams.load('tests/fixtures/valid.jams') -def test_jams_save(input_jam, output_path): +@parametrize('indent', [None, 0, 1, 2]) +def test_jams_save(input_jam, output_path, indent): - input_jam.save(output_path) + input_jam.save(output_path, indent=indent) reload_jam = jams.load(output_path) assert input_jam == reload_jam