From 0344701f1b3c99eb1b43e448fe8089c735dc2bd8 Mon Sep 17 00:00:00 2001 From: Veronica Berglyd Olsen <1619840+vkbo@users.noreply.github.com> Date: Sun, 5 Oct 2025 17:13:40 +0200 Subject: [PATCH] Add helper function to combine JSON strings as larger JSON file --- novelwriter/common.py | 6 ++++++ tests/test_base/test_base_common.py | 19 +++++++++++++++---- tests/tools.py | 4 ++-- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/novelwriter/common.py b/novelwriter/common.py index 8fd9386a..5bd35d50 100644 --- a/novelwriter/common.py +++ b/novelwriter/common.py @@ -560,6 +560,12 @@ def jsonEncode(data: dict | list | tuple, n: int = 0, nmax: int = 0) -> str: return "".join(buffer) +def jsonCombine(data: dict[str, str]) -> str: + """Combine multiple already packed JSON strings.""" + payload = ",\n".join(f' "{k}": {v}' for k, v in data.items()) + return f"{{\n{payload}\n}}\n" + + ## # XML Helpers ## diff --git a/tests/test_base/test_base_common.py b/tests/test_base/test_base_common.py index 95d339df..7ba2ddb0 100644 --- a/tests/test_base/test_base_common.py +++ b/tests/test_base/test_base_common.py @@ -36,10 +36,10 @@ from novelwriter.common import ( describeFont, elide, encodeMimeHandles, firstFloat, fontMatcher, formatFileFilter, formatInt, formatTime, formatTimeStamp, formatVersion, fuzzyTime, getFileSize, hexToInt, isHandle, isItemClass, isItemLayout, - isItemType, isListInstance, isTitleTag, jsonEncode, makeFileNameSafe, - minmax, numberToRoman, openExternalPath, processDialogSymbols, - readTextFile, simplified, transferCase, uniqueCompact, utf16CharMap, - xmlElement, xmlIndent, xmlSubElem, yesNo + isItemType, isListInstance, isTitleTag, jsonCombine, jsonEncode, + makeFileNameSafe, minmax, numberToRoman, openExternalPath, + processDialogSymbols, readTextFile, simplified, transferCase, + uniqueCompact, utf16CharMap, xmlElement, xmlIndent, xmlSubElem, yesNo ) from novelwriter.enum import nwItemClass @@ -651,6 +651,17 @@ def testBaseCommon_jsonEncode(): ) +@pytest.mark.base +def testBaseCommon_jsonCombine(): + """Test the jsonCombine function.""" + assert jsonCombine({"a": "[1, 2]", "b": "[3, 4]"}) == ( + '{\n' + ' "a": [1, 2],\n' + ' "b": [3, 4]\n' + '}\n' + ) + + @pytest.mark.base def testBaseCommon_xmlIndent(): """Test the xmlIndent function.""" diff --git a/tests/tools.py b/tests/tools.py index 9eec20d0..5d0b7c84 100644 --- a/tests/tools.py +++ b/tests/tools.py @@ -66,8 +66,8 @@ class C: def cmpFiles( fileOne: str | Path, fileTwo: str | Path, - ignoreLines: list | None = None, - ignoreStart: tuple | None = None + ignoreLines: list[int] | None = None, + ignoreStart: tuple[str] | None = None ) -> bool: """Compare two files, with optional line ignore.""" if ignoreLines is None: