From 742b26b920e2576180ac691d9e6b265699505c20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Randi=20Katrine=20Hiller=C3=B8e?= Date: Wed, 15 Nov 2017 12:46:02 +0100 Subject: [PATCH] Issue with replacing more than wanted When finding array matches only the content of the array is replaced. This content can potentially be present in multiple places and will then break later array replacements. The below example can reproduce the issue: { "test": [3, 4], "test2": [1, 2, 3, 4], "test3": [3, 4] } With setting "keep_arrays_single_line": true Basically the issue occurs for two arrays A, B where A is a suffix of B and A occurs earlier in the JSON document than B. The fix is to match the whole array, not just the content. Then remove the brackets to split and join and re-add the brackets afterwards. If the same array occurs multiple times then this will replace all instances during the first replace, however that should not cause any issues. The fix prevents issues with replacing arrays that are subsets of other arrays. --- PrettyJson.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/PrettyJson.py b/PrettyJson.py index a3432c9..1317cfa 100644 --- a/PrettyJson.py +++ b/PrettyJson.py @@ -89,11 +89,12 @@ class PrettyJsonBaseCommand: if post_process: # find all array matches - matches = re.findall(r"\[([^\[\]]+?)\]", output_json) + matches = re.findall(r"(\[[^\[\]]+?\])", output_json) join_separator = line_separator.ljust(2) for m in matches: - items = [a.strip() for a in m.split(line_separator.strip())] - replacement = join_separator.join(items) + content = m[1:-1] + items = [a.strip() for a in content.split(line_separator.strip())] + replacement = "[" + join_separator.join(items) + "]" # if line not gets too long, replace with single line if len(replacement) <= s.get("max_arrays_line_length", 120): output_json = output_json.replace(m, replacement)