From 317a1a35b0b13b66c4cdaf0b602a13778fd12045 Mon Sep 17 00:00:00 2001 From: TheSecEng Date: Tue, 18 Aug 2020 12:37:01 -0400 Subject: [PATCH 01/12] fix json format on save, fix json / xml syntax files for ST4, fix jq query, fix double to single quote --- Pretty JSON.sublime-settings | 9 ++-- PrettyJson.py | 93 +++++++++++++++++++++--------------- PrettyJsonListeners.py | 18 +++---- 3 files changed, 67 insertions(+), 53 deletions(-) diff --git a/Pretty JSON.sublime-settings b/Pretty JSON.sublime-settings index 613f31a..d0f8b52 100644 --- a/Pretty JSON.sublime-settings +++ b/Pretty JSON.sublime-settings @@ -19,9 +19,10 @@ "jq_binary": "jq", "jq_errors": false, "as_json":[ - "Packages/JSON/JSON.sublime-syntax", - "Packages/PackageDev/Package/Sublime Text Commands/Sublime Text Commands.sublime-syntax", - "Packages/PackageDev/Package/Sublime Text Settings/Sublime Text Settings.sublime-syntax", - "Packages/PackageDev/Package/Sublime Text Menu/Sublime Text Menu.sublime-syntax" + "Packages/JSON/JSON.tmLanguage", + "Packages/JSON/JSON.sublime-syntax", + "Packages/PackageDev/Package/Sublime Text Commands/Sublime Text Commands.sublime-syntax", + "Packages/PackageDev/Package/Sublime Text Settings/Sublime Text Settings.sublime-syntax", + "Packages/PackageDev/Package/Sublime Text Menu/Sublime Text Menu.sublime-syntax" ] } \ No newline at end of file diff --git a/PrettyJson.py b/PrettyJson.py index cb1345d..6cef245 100644 --- a/PrettyJson.py +++ b/PrettyJson.py @@ -15,10 +15,10 @@ from .lib.simplejson import OrderedDict PREVIOUS_CONTENT = [str(), str()] PREVIOUS_QUERY_LEN = int() -s = sublime.load_settings('Pretty JSON.sublime-settings') +s = {} -xml_syntax = 'Packages/XML/XML.tmLanguage' -json_syntax = 'Packages/JSON/JSON.tmLanguage' +xml_syntax = 'Packages/XML/XML.sublime-syntax' +json_syntax = 'Packages/JSON/JSON.sublime-syntax' jq_exists = bool() jq_init = bool() @@ -89,10 +89,10 @@ class PrettyJsonBaseCommand: replacement = f'[{join_separator.join(items)}]' if len(replacement) <= s.get('max_arrays_line_length', 120): output_json = output_json.replace(m, replacement, 1) - elif s.get("bracket_newline", True): + elif s.get('bracket_newline', True): output_json = PrettyJsonBaseCommand.bracket_newline.sub(r'\1\n\2\3', output_json) - if s.get("brace_newline", True): + if s.get('brace_newline', True): output_json = PrettyJsonBaseCommand.brace_newline.sub(r'\1\n\2\3', output_json) return output_json @@ -104,7 +104,7 @@ class PrettyJsonBaseCommand: entire_file = False if region.empty() and regions_length > 1: return None, None - elif region.empty() and s.get("use_entire_file_if_no_selection", True): + elif region.empty() and s.get('use_entire_file_if_no_selection', True): region = sublime.Region(0, view.size()) entire_file = True @@ -212,13 +212,13 @@ class PrettyJsonValidate(PrettyJsonBaseCommand, sublime_plugin.TextCommand): self.show_exception(region=region, msg=ex) return - sublime.status_message("JSON Valid") + sublime.status_message('JSON Valid') def duplicate_key_hook(self, pairs): result = dict() for key, val in pairs: if key in result: - raise KeyError(f"Duplicate key specified: {key}") + raise KeyError(f'Duplicate key specified: {key}') result[key] = val return result @@ -255,15 +255,15 @@ class PrettyJsonCommand(PrettyJsonBaseCommand, sublime_plugin.TextCommand): except Exception as ex: try: count_single_quotes = re.findall( - r"(\'[^\']+\'?)", selection_text + r'(\'[^\']+\'?)', selection_text ) amount_of_double_quotes = re.findall( - r"(\"[^\"]+\"?)", selection_text + r'(\"[^\"]+\"?)', selection_text ) if len(count_single_quotes) >= len(amount_of_double_quotes): modified_text = re.sub( - r"(?:\'([^\']+)\'?)", r'"\1"', selection_text + r'(?:\'([^\']+)\'?)', r'"\1"', selection_text ) obj = self.json_loads(modified_text) json_text = self.json_dumps(obj=obj, minified=False) @@ -281,7 +281,7 @@ class PrettyJsonCommand(PrettyJsonBaseCommand, sublime_plugin.TextCommand): class PrettyJsonAndSortCommand(PrettyJsonCommand, sublime_plugin.TextCommand): - ''' + ''' Description: Pretty print json with forced sorting ''' @@ -322,44 +322,47 @@ class UnPrettyJsonCommand(PrettyJsonBaseCommand, sublime_plugin.TextCommand): class JqInsertPrettyJsonCommand(sublime_plugin.TextCommand): def run(self, edit, string): + self.view.set_read_only(False) self.view.replace(edit, sublime.Region(0, self.view.size()), string) + self.view.set_read_only(True) class JqPrettyJsonCommand(sublime_plugin.TextCommand): def run(self, edit): - original_view = self.view - syntax_file = original_view.settings().get("syntax") + syntax_file = self.view.settings().get('syntax') - total_region = sublime.Region(0, original_view.size()) - content = original_view.substr(total_region) + total_region = sublime.Region(0, self.view.size()) + content = self.view.substr(total_region) - sublime.run_command("new_window") + sublime.run_command('new_window') preview_window = sublime.active_window() preview_window.run_command( - "set_layout", + 'set_layout', { - "cols": [0.0, 0.5, 1.0], - "rows": [0.0, 1.0], - "cells": [[0, 0, 1, 1], [1, 0, 2, 1]], + 'cols': [0.0, 0.5, 1.0], + 'rows': [0.0, 1.0], + 'cells': [[0, 0, 1, 1], [1, 0, 2, 1]], }, ) preview_window.focus_group(1) preview_view = preview_window.new_file() preview_view.set_scratch(True) - preview_view.set_name("Preview") + preview_view.set_read_only(True) + preview_view.set_name('Preview') preview_view.sel().clear() preview_window.focus_group(0) + jq_view = preview_window.new_file() - jq_view.run_command("jq_insert_pretty_json", {"string": content}) + jq_view.run_command('jq_insert_pretty_json', {'string': content}) jq_view.set_read_only(True) jq_view.set_scratch(True) jq_view.sel().clear() jq_view.set_syntax_file(syntax_file) - preview_view.set_syntax_file(json_syntax) + preview_view.set_syntax_file(syntax_file) class JqQueryPrettyJson(sublime_plugin.WindowCommand): @@ -367,23 +370,35 @@ class JqQueryPrettyJson(sublime_plugin.WindowCommand): Description: ./jq integration """ + def is_enabled(self): + as_json = s.get('as_json', ['JSON']) + return any( + syntax in self.window.active_view().settings().get('syntax') for syntax in as_json + ) + + def is_visible(self): + as_json = s.get('as_json', ['JSON']) + return any( + syntax in self.window.active_view().settings().get('syntax') for syntax in as_json + ) + def run(self): check_jq() if jq_exists: preview_view = self.window.active_view() - preview_view.run_command("jq_pretty_json") + preview_view.run_command('jq_pretty_json') sublime.active_window().show_input_panel( - "Enter ./jq filter expression", ".", self.done, self.send_query, None, + 'Enter ./jq filter expression', '.', self.done, self.send_query, None, ) else: sublime.status_message( - "./jq tool is not available on your system. http://stedolan.github.io/jq" + './jq tool is not available on your system. http://stedolan.github.io/jq' ) def get_content(self): """ returns content of active view or selected region """ - view = self.window.active_view_in_group(0) - selection = str() + view = self.window.active_view() + selection = '' regions = view.sel() for region in regions: if region.empty() and len(regions) > 1: @@ -405,16 +420,18 @@ class JqQueryPrettyJson(sublime_plugin.WindowCommand): ) QUERY_LEN = len(query) raw_json = self.get_content() - if PREVIOUS_CONTENT[0] == "": + + if not PREVIOUS_CONTENT[0]: PREVIOUS_CONTENT[0] = raw_json - if PREVIOUS_CONTENT[1] == "": + if not PREVIOUS_CONTENT[1]: PREVIOUS_CONTENT[1] = raw_json - out, err = p.communicate(bytes(raw_json, "UTF-8")) - output = out.decode("UTF-8").replace(os.linesep, "\n").strip() - errors = err.decode("UTF-8").replace(os.linesep, "\n").strip() + out, err = p.communicate(bytes(raw_json, 'UTF-8')) + output = out.decode('UTF-8').replace(os.linesep, '\n').strip() + errors = err.decode('UTF-8').replace(os.linesep, '\n').strip() jq_view = sublime.active_window().active_view_in_group(1) - if output and output != "null": + + if output and output != 'null': if QUERY_LEN > PREVIOUS_QUERY_LEN: PREVIOUS_CONTENT[0] = PREVIOUS_CONTENT[1] PREVIOUS_CONTENT[1] = output @@ -422,14 +439,14 @@ class JqQueryPrettyJson(sublime_plugin.WindowCommand): PREVIOUS_CONTENT[1] = PREVIOUS_CONTENT[0] PREVIOUS_CONTENT[0] = output PREVIOUS_QUERY_LEN = len(query) - elif s.get("jq_errors", False) and errors: - output = errors + elif s.get('jq_errors', False) and errors: + output = errors else: if PREVIOUS_QUERY_LEN <= QUERY_LEN: output = PREVIOUS_CONTENT[1] else: output = PREVIOUS_CONTENT[0] - jq_view.run_command("jq_insert_pretty_json", {"string": output}) + jq_view.run_command('jq_insert_pretty_json', {'string': output}) except OSError as ex: sublime.status_message(str(ex)) diff --git a/PrettyJsonListeners.py b/PrettyJsonListeners.py index e49851b..573dabd 100644 --- a/PrettyJsonListeners.py +++ b/PrettyJsonListeners.py @@ -8,13 +8,11 @@ s = sublime.load_settings("Pretty JSON.sublime-settings") class PrettyJsonLintListener(sublime_plugin.EventListener, PrettyJsonBaseCommand): def on_post_save(self, view): - if not s.get('validate_on_save', True): + if not s.get("validate_on_save", True): return - as_json = s.get('as_json', ['JSON']) - if any( - syntax in view.settings().get("syntax") for syntax in as_json - ): + as_json = s.get("as_json", ["JSON"]) + if any(syntax in view.settings().get("syntax") for syntax in as_json): self.view = view self.clear_phantoms() json_content = view.substr(sublime.Region(0, view.size())) @@ -26,11 +24,9 @@ class PrettyJsonLintListener(sublime_plugin.EventListener, PrettyJsonBaseCommand class PrettyJsonAutoPrettyOnSaveListener(sublime_plugin.EventListener): def on_pre_save(self, view): - if not s.get('pretty_on_save', False): + if not s.get("pretty_on_save", False): return - as_json = s.get('as_json', ['JSON']) - if any( - syntax in view.settings().get('syntax') for syntax in as_json - ): - sublime.active_window().active_view().run_command('pretty_json') + as_json = s.get("as_json", ["JSON"]) + if any(syntax in view.settings().get("syntax") for syntax in as_json): + view.run_command("pretty_json") From 2d0881d480bd9c8a20fd1439aa9b71efb063b1f2 Mon Sep 17 00:00:00 2001 From: TheSecEng Date: Tue, 18 Aug 2020 12:39:50 -0400 Subject: [PATCH 02/12] remove old json syntax from ST3 --- Pretty JSON.sublime-settings | 1 - 1 file changed, 1 deletion(-) diff --git a/Pretty JSON.sublime-settings b/Pretty JSON.sublime-settings index d0f8b52..bb6c870 100644 --- a/Pretty JSON.sublime-settings +++ b/Pretty JSON.sublime-settings @@ -19,7 +19,6 @@ "jq_binary": "jq", "jq_errors": false, "as_json":[ - "Packages/JSON/JSON.tmLanguage", "Packages/JSON/JSON.sublime-syntax", "Packages/PackageDev/Package/Sublime Text Commands/Sublime Text Commands.sublime-syntax", "Packages/PackageDev/Package/Sublime Text Settings/Sublime Text Settings.sublime-syntax", From f36ac3dde3ecc1106f41d885826044dade23a53d Mon Sep 17 00:00:00 2001 From: TheSecEng Date: Tue, 4 May 2021 08:04:39 -0700 Subject: [PATCH 03/12] minor code fixes, remove key bindings --- Default (Linux).sublime-keymap | 26 +++++++++++----------- Default (OSX).sublime-keymap | 26 +++++++++++----------- Default (Windows).sublime-keymap | 38 ++++++++++++++++---------------- Default.sublime-commands | 3 ++- PrettyJson.py | 14 +++++++++--- 5 files changed, 58 insertions(+), 49 deletions(-) diff --git a/Default (Linux).sublime-keymap b/Default (Linux).sublime-keymap index 4ce5b0d..e655c91 100644 --- a/Default (Linux).sublime-keymap +++ b/Default (Linux).sublime-keymap @@ -1,15 +1,15 @@ [ - { - "keys": [ - "ctrl+alt+j" - ], - "command": "pretty_json" - }, - { - "keys": ["ctrl+r"], - "command": "pretty_json_goto_symbol", - "context": [ - { "key": "selector", "operator": "equal", "operand": "source.json" } - ] - } + // { + // "keys": [ + // "ctrl+alt+j" + // ], + // "command": "pretty_json" + // }, + // { + // "keys": ["ctrl+r"], + // "command": "pretty_json_goto_symbol", + // "context": [ + // { "key": "selector", "operator": "equal", "operand": "source.json" } + // ] + // } ] \ No newline at end of file diff --git a/Default (OSX).sublime-keymap b/Default (OSX).sublime-keymap index e7ce965..e634c12 100644 --- a/Default (OSX).sublime-keymap +++ b/Default (OSX).sublime-keymap @@ -1,15 +1,15 @@ [ - { - "keys": [ - "super+ctrl+j" - ], - "command": "pretty_json" - }, - { - "keys": ["super+r"], - "command": "pretty_json_goto_symbol", - "context": [ - { "key": "selector", "operator": "equal", "operand": "source.json" } - ] - } + // { + // "keys": [ + // "super+ctrl+j" + // ], + // "command": "pretty_json" + // }, + // { + // "keys": ["super+r"], + // "command": "pretty_json_goto_symbol", + // "context": [ + // { "key": "selector", "operator": "equal", "operand": "source.json" } + // ] + // } ] \ No newline at end of file diff --git a/Default (Windows).sublime-keymap b/Default (Windows).sublime-keymap index a1e794b..bf57c8d 100644 --- a/Default (Windows).sublime-keymap +++ b/Default (Windows).sublime-keymap @@ -1,22 +1,22 @@ [ - { - "keys": [ - "ctrl+alt+j" - ], - "command": "pretty_json" - }, - { - "keys": [ - "ctrl+alt+m" - ], - "command": "un_pretty_json" - }, - { - "keys": ["ctrl+r"], - "command": "pretty_json_goto_symbol", - "context": [ - { "key": "selector", "operator": "equal", "operand": "source.json" } - ] - } + // { + // "keys": [ + // "ctrl+alt+j" + // ], + // "command": "pretty_json" + // }, + // { + // "keys": [ + // "ctrl+alt+m" + // ], + // "command": "un_pretty_json" + // }, + // { + // "keys": ["ctrl+r"], + // "command": "pretty_json_goto_symbol", + // "context": [ + // { "key": "selector", "operator": "equal", "operand": "source.json" } + // ] + // } ] diff --git a/Default.sublime-commands b/Default.sublime-commands index 774e20a..d9e9df0 100644 --- a/Default.sublime-commands +++ b/Default.sublime-commands @@ -26,7 +26,8 @@ { "caption": "Preferences: Pretty JSON Settings", "command": "edit_settings", - "args": { + "args": + { "base_file": "${packages}/Pretty JSON/Pretty JSON.sublime-settings", "default": "{\n\t$0\n}\n" } diff --git a/PrettyJson.py b/PrettyJson.py index 6cef245..df72059 100644 --- a/PrettyJson.py +++ b/PrettyJson.py @@ -50,7 +50,7 @@ class PrettyJsonBaseCommand: bracket_newline = re.compile(r'^((\s*)".*?":)\s*([\[])', re.MULTILINE) @staticmethod - def json_loads(selection: str, object_pairs_hook=OrderedDict) -> dict: + def json_loads(selection: str, object_pairs_hook=OrderedDict): return json.loads( selection, object_pairs_hook=object_pairs_hook, parse_float=decimal.Decimal ) @@ -100,7 +100,7 @@ class PrettyJsonBaseCommand: @staticmethod def get_selection_from_region( region: sublime.Region, regions_length: int, view: sublime.View - ) -> sublime.Region: + ): entire_file = False if region.empty() and regions_length > 1: return None, None @@ -110,9 +110,10 @@ class PrettyJsonBaseCommand: return region, entire_file - def reindent(self, text: str, selection: str): + def reindent(self, text: str, selection: sublime.Region): current_line = self.view.line(selection.begin()) text_before_sel = sublime.Region(current_line.begin(), selection.begin()) + indent_space = '' reindent_mode = s.get('reindent_block', False) if reindent_mode == 'start': @@ -371,12 +372,18 @@ class JqQueryPrettyJson(sublime_plugin.WindowCommand): """ def is_enabled(self): + if not self.window: + return + as_json = s.get('as_json', ['JSON']) return any( syntax in self.window.active_view().settings().get('syntax') for syntax in as_json ) def is_visible(self): + if not self.window: + return + as_json = s.get('as_json', ['JSON']) return any( syntax in self.window.active_view().settings().get('syntax') for syntax in as_json @@ -423,6 +430,7 @@ class JqQueryPrettyJson(sublime_plugin.WindowCommand): if not PREVIOUS_CONTENT[0]: PREVIOUS_CONTENT[0] = raw_json + if not PREVIOUS_CONTENT[1]: PREVIOUS_CONTENT[1] = raw_json From b7af5505264c3a15f4d43805fd593486b64ca06d Mon Sep 17 00:00:00 2001 From: TheSecEng Date: Tue, 4 May 2021 08:27:11 -0700 Subject: [PATCH 04/12] Update README --- PrettyJson.py | 4 ++-- PrettyJsonListeners.py | 1 - README.md | 22 ++++++++++++++-------- 3 files changed, 16 insertions(+), 11 deletions(-) diff --git a/PrettyJson.py b/PrettyJson.py index df72059..1422d48 100644 --- a/PrettyJson.py +++ b/PrettyJson.py @@ -37,7 +37,7 @@ def check_jq(): jq_path = shutil.which(jq_test) jq_exists = True except OSError as ex: - print(str(ex)) + sublime.message_dialog(f'[Error]: {ex}') jq_exists = False @@ -240,8 +240,8 @@ class PrettyJsonCommand(PrettyJsonBaseCommand, sublime_plugin.TextCommand): if region is None: continue + selection_text = self.view.substr(region) try: - selection_text = self.view.substr(region) obj = self.json_loads(selection_text) json_text = self.json_dumps(obj=obj, minified=False) diff --git a/PrettyJsonListeners.py b/PrettyJsonListeners.py index 573dabd..7311113 100644 --- a/PrettyJsonListeners.py +++ b/PrettyJsonListeners.py @@ -13,7 +13,6 @@ class PrettyJsonLintListener(sublime_plugin.EventListener, PrettyJsonBaseCommand as_json = s.get("as_json", ["JSON"]) if any(syntax in view.settings().get("syntax") for syntax in as_json): - self.view = view self.clear_phantoms() json_content = view.substr(sublime.Region(0, view.size())) try: diff --git a/README.md b/README.md index a534c84..0b4c04c 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,20 @@ Prettify/Minify/Query/Goto/Validate/Lint JSON plugin for Sublime Text 3 & 4 +## Updates + +All keybindings have been removed in favor of the Command Palette. And to allow +for users to configure their own specific key bindings. + +This also prevents key binding overrides which conflict with other packages. For +good documentation on key bindings I recommend you review the [Offical Docs][] or +[Community Docs][] + ## Installation ### Package Control (Recommended) -Install this sublime text 3/4 package via [Package Control][] +Install this sublime text 3 / 4 package via [Package Control][] search for package: "[**Pretty JSON**][]" ### Manual Installation @@ -29,13 +38,7 @@ No longer supported ## Usage To prettify JSON, make selection of json -(or else it will try to use full view buffer) and press keys: - -- Linux: ctrl+alt+j -- Windows: ctrl+alt+j -- OS X: cmd+ctrl+j - -or through Command Palette Ctrl+Shift+P +(or else it will try to use full view buffer) and through Command Palette Ctrl+Shift+P find "Pretty JSON: Format JSON" (you can search for part of it like 'pretty format') @@ -192,3 +195,6 @@ If you YAMLing then maybe you interested in this plugin: [PrettyYAML][] [**Pretty JSON**]: https://packagecontrol.io/packages/Pretty%20JSON [PrettyYAML]: https://github.com/aukaost/SublimePrettyYAML [./jq]: http://stedolan.github.io/jq/ +[Offical Docs]: https://www.sublimetext.com/docs/key_bindings.html +[Community Docs]: https://docs.sublimetext.io/guide/customization/key_bindings.html + From 51859d62e86e7cb4a677276f6530e91ac249424b Mon Sep 17 00:00:00 2001 From: TheSecEng Date: Tue, 25 May 2021 15:58:22 -0700 Subject: [PATCH 05/12] fix: case when window or active_view is none --- PrettyJson.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/PrettyJson.py b/PrettyJson.py index 1422d48..c1a9d2c 100644 --- a/PrettyJson.py +++ b/PrettyJson.py @@ -375,18 +375,26 @@ class JqQueryPrettyJson(sublime_plugin.WindowCommand): if not self.window: return + view = self.window.active_view() + if not view: + return + as_json = s.get('as_json', ['JSON']) return any( - syntax in self.window.active_view().settings().get('syntax') for syntax in as_json + syntax in view.settings().get('syntax', '') for syntax in as_json ) def is_visible(self): if not self.window: return + view = self.window.active_view() + if not view: + return + as_json = s.get('as_json', ['JSON']) return any( - syntax in self.window.active_view().settings().get('syntax') for syntax in as_json + syntax in view.settings().get('syntax', '') for syntax in as_json ) def run(self): From a960fb828d614c93916803b3b127675ecbb3d41f Mon Sep 17 00:00:00 2001 From: TheSecEng Date: Tue, 25 May 2021 16:50:36 -0700 Subject: [PATCH 06/12] fix: keep_arrays_single_line issue where it splits on `,` in the middle of a string --- PrettyJson.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/PrettyJson.py b/PrettyJson.py index c1a9d2c..5a018af 100644 --- a/PrettyJson.py +++ b/PrettyJson.py @@ -83,12 +83,13 @@ class PrettyJsonBaseCommand: matches.sort(key=len, reverse=True) join_separator = line_separator.ljust(2) for m in matches: - content = m[1:-1] - items = [a.strip() for a in content.split(line_separator.strip())] - + content = m[1:-1].strip() + items = [a.strip() for a in content.split(os.linesep)] + items = [item[:-1] if item[-1] == ',' else item for item in items] replacement = f'[{join_separator.join(items)}]' if len(replacement) <= s.get('max_arrays_line_length', 120): output_json = output_json.replace(m, replacement, 1) + elif s.get('bracket_newline', True): output_json = PrettyJsonBaseCommand.bracket_newline.sub(r'\1\n\2\3', output_json) From 8d86d63169caec7517018b89a8e346069d5aa0e4 Mon Sep 17 00:00:00 2001 From: TheSecEng Date: Wed, 26 May 2021 12:29:28 -0700 Subject: [PATCH 07/12] fix: Unloaded settings --- PrettyJson.py | 78 ++++++++++++++++++++++++--------------------------- 1 file changed, 37 insertions(+), 41 deletions(-) diff --git a/PrettyJson.py b/PrettyJson.py index 5a018af..cfabc2b 100644 --- a/PrettyJson.py +++ b/PrettyJson.py @@ -15,8 +15,6 @@ from .lib.simplejson import OrderedDict PREVIOUS_CONTENT = [str(), str()] PREVIOUS_QUERY_LEN = int() -s = {} - xml_syntax = 'Packages/XML/XML.sublime-syntax' json_syntax = 'Packages/JSON/JSON.sublime-syntax' @@ -27,12 +25,13 @@ jq_path = str() def check_jq(): global jq_init, jq_exists, jq_path + settings = sublime.load_settings('Pretty JSON.sublime-settings') if jq_init: return jq_init = True - jq_test = s.get('jq_binary', 'jq') + jq_test = settings.get('jq_binary', 'jq') try: jq_path = shutil.which(jq_test) jq_exists = True @@ -57,20 +56,22 @@ class PrettyJsonBaseCommand: @staticmethod def json_dumps(obj, minified: bool = False) -> str: - sort_keys = s.get('sort_keys', False) + settings = sublime.load_settings('Pretty JSON.sublime-settings') + + sort_keys = settings.get('sort_keys', False) if PrettyJsonBaseCommand.force_sorting: sort_keys = True - line_separator = s.get('line_separator', ',') - value_separator = s.get('value_separator', ': ') + line_separator = settings.get('line_separator', ',') + value_separator = settings.get('value_separator', ': ') if minified: line_separator = line_separator.strip() value_separator = value_separator.strip() output_json = json.dumps( obj, - indent=None if minified else s.get('indent', 2), - ensure_ascii=s.get('ensure_ascii', False), + indent=None if minified else settings.get('indent', 2), + ensure_ascii=settings.get('ensure_ascii', False), sort_keys=sort_keys, separators=(line_separator, value_separator), use_decimal=True, @@ -78,7 +79,7 @@ class PrettyJsonBaseCommand: if minified: return output_json - if s.get('keep_arrays_single_line', False): + if settings.get('keep_arrays_single_line', False): matches = re.findall(r'(\[[^\[\]]+?\])', output_json) matches.sort(key=len, reverse=True) join_separator = line_separator.ljust(2) @@ -87,13 +88,13 @@ class PrettyJsonBaseCommand: items = [a.strip() for a in content.split(os.linesep)] items = [item[:-1] if item[-1] == ',' else item for item in items] replacement = f'[{join_separator.join(items)}]' - if len(replacement) <= s.get('max_arrays_line_length', 120): + if len(replacement) <= settings.get('max_arrays_line_length', 120): output_json = output_json.replace(m, replacement, 1) - elif s.get('bracket_newline', True): + elif settings.get('bracket_newline', True): output_json = PrettyJsonBaseCommand.bracket_newline.sub(r'\1\n\2\3', output_json) - if s.get('brace_newline', True): + if settings.get('brace_newline', True): output_json = PrettyJsonBaseCommand.brace_newline.sub(r'\1\n\2\3', output_json) return output_json @@ -102,21 +103,23 @@ class PrettyJsonBaseCommand: def get_selection_from_region( region: sublime.Region, regions_length: int, view: sublime.View ): + settings = sublime.load_settings('Pretty JSON.sublime-settings') entire_file = False if region.empty() and regions_length > 1: return None, None - elif region.empty() and s.get('use_entire_file_if_no_selection', True): + elif region.empty() and settings.get('use_entire_file_if_no_selection', True): region = sublime.Region(0, view.size()) entire_file = True return region, entire_file def reindent(self, text: str, selection: sublime.Region): + settings = sublime.load_settings('Pretty JSON.sublime-settings') current_line = self.view.line(selection.begin()) text_before_sel = sublime.Region(current_line.begin(), selection.begin()) indent_space = '' - reindent_mode = s.get('reindent_block', False) + reindent_mode = settings.get('reindent_block', False) if reindent_mode == 'start': space_number = text_before_sel.size() indent_space = ' ' * space_number @@ -190,8 +193,9 @@ class PrettyJsonBaseCommand: self.phantom_set.update(self.phantoms) def syntax_to_json(self): + settings = sublime.load_settings('Pretty JSON.sublime-settings') syntax = os.path.splitext(os.path.basename(self.view.settings().get('syntax')))[0] - as_json = [i.lower() for i in s.get('as_json', ['JSON'])] + as_json = [i.lower() for i in settings.get('as_json', ['JSON'])] if syntax.lower() not in as_json: self.view.set_syntax_file(json_syntax) @@ -231,6 +235,8 @@ class PrettyJsonCommand(PrettyJsonBaseCommand, sublime_plugin.TextCommand): ''' def run(self, edit): + settings = sublime.load_settings('Pretty JSON.sublime-settings') + self.clear_phantoms() regions = self.view.sel() for region in regions: @@ -246,7 +252,7 @@ class PrettyJsonCommand(PrettyJsonBaseCommand, sublime_plugin.TextCommand): obj = self.json_loads(selection_text) json_text = self.json_dumps(obj=obj, minified=False) - if not entire_file and s.get('reindent_block', False): + if not entire_file and settings.get('reindent_block', False): json_text = self.reindent(json_text, region) self.view.replace(edit, region, json_text) @@ -270,7 +276,7 @@ class PrettyJsonCommand(PrettyJsonBaseCommand, sublime_plugin.TextCommand): obj = self.json_loads(modified_text) json_text = self.json_dumps(obj=obj, minified=False) - if not entire_file and s.get('reindent_block', False): + if not entire_file and settings.get('reindent_block', False): json_text = self.reindent(json_text, region) self.view.replace(edit, region, json_text) @@ -373,6 +379,8 @@ class JqQueryPrettyJson(sublime_plugin.WindowCommand): """ def is_enabled(self): + settings = sublime.load_settings('Pretty JSON.sublime-settings') + if not self.window: return @@ -380,23 +388,13 @@ class JqQueryPrettyJson(sublime_plugin.WindowCommand): if not view: return - as_json = s.get('as_json', ['JSON']) + as_json = settings.get('as_json', ['JSON']) return any( syntax in view.settings().get('syntax', '') for syntax in as_json ) def is_visible(self): - if not self.window: - return - - view = self.window.active_view() - if not view: - return - - as_json = s.get('as_json', ['JSON']) - return any( - syntax in view.settings().get('syntax', '') for syntax in as_json - ) + return self.is_enabled() def run(self): check_jq() @@ -427,13 +425,14 @@ class JqQueryPrettyJson(sublime_plugin.WindowCommand): def send_query(self, query: str): global PREVIOUS_CONTENT, PREVIOUS_QUERY_LEN + settings = sublime.load_settings('Pretty JSON.sublime-settings') try: p = subprocess.Popen( - [jq_path, query], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - stdin=subprocess.PIPE, - ) + [jq_path, query], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + stdin=subprocess.PIPE, + ) QUERY_LEN = len(query) raw_json = self.get_content() @@ -456,7 +455,7 @@ class JqQueryPrettyJson(sublime_plugin.WindowCommand): PREVIOUS_CONTENT[1] = PREVIOUS_CONTENT[0] PREVIOUS_CONTENT[0] = output PREVIOUS_QUERY_LEN = len(query) - elif s.get('jq_errors', False) and errors: + elif settings.get('jq_errors', False) and errors: output = errors else: if PREVIOUS_QUERY_LEN <= QUERY_LEN: @@ -479,6 +478,8 @@ class JsonToXml(PrettyJsonBaseCommand, sublime_plugin.TextCommand): ''' def run(self, edit): + settings = sublime.load_settings('Pretty JSON.sublime-settings') + self.clear_phantoms() regions = self.view.sel() for region in regions: @@ -504,7 +505,7 @@ class JsonToXml(PrettyJsonBaseCommand, sublime_plugin.TextCommand): if type(xml_string) is bytes: xml_string = xml_string.decode('utf-8') - if not entire_file and s.get('reindent_block', False): + if not entire_file and settings.get('reindent_block', False): xml_string = self.reindent(xml_string, region) self.view.replace(edit, region, xml_string) @@ -584,8 +585,3 @@ class PrettyJsonGotoSymbolCommand(PrettyJsonBaseCommand, sublime_plugin.TextComm self.view.sel().clear() self.view.sel().add(region) self.view.show(region) - - -def plugin_loaded(): - global s - s = sublime.load_settings('Pretty JSON.sublime-settings') From 6cffc27ce5d1cb0a54ba05eddbdea456a76d1160 Mon Sep 17 00:00:00 2001 From: TheSecEng Date: Wed, 26 May 2021 13:42:41 -0700 Subject: [PATCH 08/12] revert ensure_ascii default --- Pretty JSON.sublime-settings | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Pretty JSON.sublime-settings b/Pretty JSON.sublime-settings index bb6c870..efe77e8 100644 --- a/Pretty JSON.sublime-settings +++ b/Pretty JSON.sublime-settings @@ -2,7 +2,7 @@ "use_entire_file_if_no_selection": true, "indent": 4, "sort_keys": false, - "ensure_ascii": true, + "ensure_ascii": false, "line_separator": ",", "value_separator": ": ", "keep_arrays_single_line": false, From 34dfb524ac60222ce384d5ec914e6fd44e90873e Mon Sep 17 00:00:00 2001 From: Sharun Kumar <715417+sharunkumar@users.noreply.github.com> Date: Fri, 4 Jun 2021 16:38:50 +0530 Subject: [PATCH 09/12] Added: List of commands that can be mapped to shortcuts --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 0b4c04c..38a854a 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,11 @@ you can add a setting like this to your .sublime-keymap file { "keys": [ "ctrl+alt+m" ], "command": "un_pretty_json" } ``` +#### List of commands that can be mapped to shortcuts +- `pretty_json` +- `un_pretty_json` +- `pretty_json_goto_symbol` + ### Convert JSON to XML Using Command Palette Ctrl+Shift+P search for From 34c27bcd8053e135367f855d15dedd0b8179d43f Mon Sep 17 00:00:00 2001 From: TheSecEng Date: Sat, 12 Jun 2021 07:25:16 -0700 Subject: [PATCH 10/12] fix array commas --- PrettyJson.py | 331 +++++++++++++++++++++++++++++++------------------- 1 file changed, 204 insertions(+), 127 deletions(-) diff --git a/PrettyJson.py b/PrettyJson.py index cfabc2b..f4c6c5a 100644 --- a/PrettyJson.py +++ b/PrettyJson.py @@ -15,8 +15,8 @@ from .lib.simplejson import OrderedDict PREVIOUS_CONTENT = [str(), str()] PREVIOUS_QUERY_LEN = int() -xml_syntax = 'Packages/XML/XML.sublime-syntax' -json_syntax = 'Packages/JSON/JSON.sublime-syntax' +xml_syntax = "Packages/XML/XML.sublime-syntax" +json_syntax = "Packages/JSON/JSON.sublime-syntax" jq_exists = bool() jq_init = bool() @@ -25,18 +25,18 @@ jq_path = str() def check_jq(): global jq_init, jq_exists, jq_path - settings = sublime.load_settings('Pretty JSON.sublime-settings') + settings = sublime.load_settings("Pretty JSON.sublime-settings") if jq_init: return jq_init = True - jq_test = settings.get('jq_binary', 'jq') + jq_test = settings.get("jq_binary", "jq") try: jq_path = shutil.which(jq_test) jq_exists = True except OSError as ex: - sublime.message_dialog(f'[Error]: {ex}') + sublime.message_dialog(f"[Error]: {ex}") jq_exists = False @@ -44,7 +44,7 @@ class PrettyJsonBaseCommand: phantom_set = sublime.PhantomSet phantoms = list() force_sorting = False - json_char_matcher = re.compile(r'char (\d+)') + json_char_matcher = re.compile(r"char (\d+)") brace_newline = re.compile(r'^((\s*)".*?":)\s*([{])', re.MULTILINE) bracket_newline = re.compile(r'^((\s*)".*?":)\s*([\[])', re.MULTILINE) @@ -56,22 +56,22 @@ class PrettyJsonBaseCommand: @staticmethod def json_dumps(obj, minified: bool = False) -> str: - settings = sublime.load_settings('Pretty JSON.sublime-settings') + settings = sublime.load_settings("Pretty JSON.sublime-settings") - sort_keys = settings.get('sort_keys', False) + sort_keys = settings.get("sort_keys", False) if PrettyJsonBaseCommand.force_sorting: sort_keys = True - line_separator = settings.get('line_separator', ',') - value_separator = settings.get('value_separator', ': ') + line_separator = settings.get("line_separator", ",") + value_separator = settings.get("value_separator", ": ") if minified: line_separator = line_separator.strip() value_separator = value_separator.strip() output_json = json.dumps( obj, - indent=None if minified else settings.get('indent', 2), - ensure_ascii=settings.get('ensure_ascii', False), + indent=None if minified else settings.get("indent", 2), + ensure_ascii=settings.get("ensure_ascii", False), sort_keys=sort_keys, separators=(line_separator, value_separator), use_decimal=True, @@ -79,23 +79,44 @@ class PrettyJsonBaseCommand: if minified: return output_json - if settings.get('keep_arrays_single_line', False): - matches = re.findall(r'(\[[^\[\]]+?\])', output_json) + if settings.get("keep_arrays_single_line", False): + matches = re.findall(r"(\[[^\[\]]+?\])", output_json) matches.sort(key=len, reverse=True) join_separator = line_separator.ljust(2) for m in matches: content = m[1:-1].strip() items = [a.strip() for a in content.split(os.linesep)] - items = [item[:-1] if item[-1] == ',' else item for item in items] - replacement = f'[{join_separator.join(items)}]' - if len(replacement) <= settings.get('max_arrays_line_length', 120): + items = [item[:-1] if item[-1] == "," else item for item in items] + replacement = "[" + print(items) + for index, item in enumerate(items): + if item in ('{', '}'): + replacement = replacement + item + if item == '}': + if index!= len(items)-1: + print(items.index(item)) + print(len(items)-1) + replacement = replacement + ',' + else: + replacement = replacement + item + if index != len(items)-1: + if items[items.index(item)+1] != '}': + replacement = replacement + ',' + replacement = replacement + ']' + print(replacement) + + if len(replacement) <= settings.get("max_arrays_line_length", 120): output_json = output_json.replace(m, replacement, 1) - elif settings.get('bracket_newline', True): - output_json = PrettyJsonBaseCommand.bracket_newline.sub(r'\1\n\2\3', output_json) + elif settings.get("bracket_newline", True): + output_json = PrettyJsonBaseCommand.bracket_newline.sub( + r"\1\n\2\3", output_json + ) - if settings.get('brace_newline', True): - output_json = PrettyJsonBaseCommand.brace_newline.sub(r'\1\n\2\3', output_json) + if settings.get("brace_newline", True): + output_json = PrettyJsonBaseCommand.brace_newline.sub( + r"\1\n\2\3", output_json + ) return output_json @@ -103,47 +124,49 @@ class PrettyJsonBaseCommand: def get_selection_from_region( region: sublime.Region, regions_length: int, view: sublime.View ): - settings = sublime.load_settings('Pretty JSON.sublime-settings') + settings = sublime.load_settings("Pretty JSON.sublime-settings") entire_file = False if region.empty() and regions_length > 1: return None, None - elif region.empty() and settings.get('use_entire_file_if_no_selection', True): + elif region.empty() and settings.get("use_entire_file_if_no_selection", True): region = sublime.Region(0, view.size()) entire_file = True return region, entire_file def reindent(self, text: str, selection: sublime.Region): - settings = sublime.load_settings('Pretty JSON.sublime-settings') + settings = sublime.load_settings("Pretty JSON.sublime-settings") current_line = self.view.line(selection.begin()) text_before_sel = sublime.Region(current_line.begin(), selection.begin()) - indent_space = '' + indent_space = "" - reindent_mode = settings.get('reindent_block', False) - if reindent_mode == 'start': + reindent_mode = settings.get("reindent_block", False) + if reindent_mode == "start": space_number = text_before_sel.size() - indent_space = ' ' * space_number - elif reindent_mode == 'minimal': - indent_space = re.search(r'^\s*', self.view.substr(text_before_sel)).group(0) + indent_space = " " * space_number + elif reindent_mode == "minimal": + indent_space = re.search(r"^\s*", self.view.substr(text_before_sel)).group( + 0 + ) - lines = text.split('\n') + lines = text.split("\n") i = 1 while i < len(lines): - lines[i] = f'{indent_space}{lines[i]}' + lines[i] = f"{indent_space}{lines[i]}" i += 1 - return '\n'.join(lines) + return "\n".join(lines) def show_exception(self, region: sublime.Region = None, msg=str()): - sublime.message_dialog(f'[Error]: {msg}') + sublime.message_dialog(f"[Error]: {msg}") if region is None: - sublime.message_dialog(f'[Error]: {msg}') + sublime.message_dialog(f"[Error]: {msg}") return - self.highlight_error(region=region, message=f'{msg}') + self.highlight_error(region=region, message=f"{msg}") def highlight_error(self, region: sublime.Region, message: str): - self.phantom_set = sublime.PhantomSet(self.view, 'json_errors') + self.phantom_set = sublime.PhantomSet(self.view, "json_errors") char_match = self.json_char_matcher.search(message) if char_match: @@ -157,21 +180,21 @@ class PrettyJsonBaseCommand: self.phantoms.append( sublime.Phantom( region, - self.create_phantom_html(message, 'error'), + self.create_phantom_html(message, "error"), sublime.LAYOUT_BELOW, self.navigation, ) ) self.phantom_set.update(self.phantoms) self.view.show(region) - self.view.set_status('json_errors', message) + self.view.set_status("json_errors", message) - # Description: Taken from + # Description: Taken from # - https://github.com/sublimelsp/LSP/blob/master/plugin/diagnostics.py # - Thanks to the LSP Team def create_phantom_html(self, content: str, severity: str) -> str: - stylesheet = sublime.load_resource('Packages/Pretty JSON/phantom.css') - return f''' + stylesheet = sublime.load_resource("Packages/Pretty JSON/phantom.css") + return f"""
@@ -180,22 +203,24 @@ class PrettyJsonBaseCommand:
{content}
- ''' + """ def navigation(self, href: str): self.clear_phantoms() def clear_phantoms(self): if isinstance(self.phantom_set, type): - self.phantom_set = sublime.PhantomSet(self.view, 'json_errors') + self.phantom_set = sublime.PhantomSet(self.view, "json_errors") self.phantoms = list() self.phantom_set.update(self.phantoms) def syntax_to_json(self): - settings = sublime.load_settings('Pretty JSON.sublime-settings') - syntax = os.path.splitext(os.path.basename(self.view.settings().get('syntax')))[0] - as_json = [i.lower() for i in settings.get('as_json', ['JSON'])] + settings = sublime.load_settings("Pretty JSON.sublime-settings") + syntax = os.path.splitext(os.path.basename(self.view.settings().get("syntax")))[ + 0 + ] + as_json = [i.lower() for i in settings.get("as_json", ["JSON"])] if syntax.lower() not in as_json: self.view.set_syntax_file(json_syntax) @@ -206,9 +231,8 @@ class PrettyJsonValidate(PrettyJsonBaseCommand, sublime_plugin.TextCommand): regions = self.view.sel() for region in regions: region, _ = self.get_selection_from_region( - region=region, - regions_length=len(region), - view=self.view) + region=region, regions_length=len(region), view=self.view + ) if region is None: continue @@ -218,32 +242,32 @@ class PrettyJsonValidate(PrettyJsonBaseCommand, sublime_plugin.TextCommand): self.show_exception(region=region, msg=ex) return - sublime.status_message('JSON Valid') + sublime.status_message("JSON Valid") def duplicate_key_hook(self, pairs): result = dict() for key, val in pairs: if key in result: - raise KeyError(f'Duplicate key specified: {key}') + raise KeyError(f"Duplicate key specified: {key}") result[key] = val return result class PrettyJsonCommand(PrettyJsonBaseCommand, sublime_plugin.TextCommand): - ''' + """ Description: Pretty Print JSON - ''' + """ def run(self, edit): - settings = sublime.load_settings('Pretty JSON.sublime-settings') + settings = sublime.load_settings("Pretty JSON.sublime-settings") self.clear_phantoms() + pos = self.view.viewport_position() regions = self.view.sel() for region in regions: region, entire_file = self.get_selection_from_region( - region=region, - regions_length=len(region), - view=self.view) + region=region, regions_length=len(region), view=self.view + ) if region is None: continue @@ -252,34 +276,34 @@ class PrettyJsonCommand(PrettyJsonBaseCommand, sublime_plugin.TextCommand): obj = self.json_loads(selection_text) json_text = self.json_dumps(obj=obj, minified=False) - if not entire_file and settings.get('reindent_block', False): + if not entire_file and settings.get("reindent_block", False): json_text = self.reindent(json_text, region) self.view.replace(edit, region, json_text) - if entire_file: self.syntax_to_json() except Exception as ex: try: - count_single_quotes = re.findall( - r'(\'[^\']+\'?)', selection_text - ) + count_single_quotes = re.findall(r"(\'[^\']+\'?)", selection_text) amount_of_double_quotes = re.findall( - r'(\"[^\"]+\"?)', selection_text + r"(\"[^\"]+\"?)", selection_text ) if len(count_single_quotes) >= len(amount_of_double_quotes): modified_text = re.sub( - r'(?:\'([^\']+)\'?)', r'"\1"', selection_text + r"(?:\'([^\']+)\'?)", r'"\1"', selection_text ) obj = self.json_loads(modified_text) json_text = self.json_dumps(obj=obj, minified=False) - if not entire_file and settings.get('reindent_block', False): + if not entire_file and settings.get("reindent_block", False): json_text = self.reindent(json_text, region) + pos = self.view.viewport_position() self.view.replace(edit, region, json_text) + self.view.set_viewport_position(pos) + if entire_file: self.syntax_to_json() else: @@ -288,10 +312,65 @@ class PrettyJsonCommand(PrettyJsonBaseCommand, sublime_plugin.TextCommand): self.show_exception(region=region, msg=ex) +class PrettyJsonLinesCommand(PrettyJsonCommand, sublime_plugin.TextCommand): + + """ + Description: Pretty print json lines https://jsonlines.org + """ + + def run(self, edit): + self.clear_phantoms() + regions = self.view.sel() + for region in regions: + (selection, selected_entire_file,) = self.get_selection_from_region( + region=region, regions_length=len(regions), view=self.view + ) + if selection is None: + continue + + for jsonl in sorted(self.view.split_by_newlines(selection), reverse=True): + if self.view.substr(jsonl).strip() == "": + continue + + if jsonl.empty() and len(jsonl) > 1: + continue + + try: + selection_text = self.view.substr(jsonl) + obj = self.json_loads(selection_text) + self.view.replace(edit, jsonl, self.json_dumps(obj)) + + if selected_entire_file: + self.syntax_to_json() + + except Exception: + try: + amount_of_single_quotes = re.findall( + r"(\'[^\']+\'?)", selection_text + ) + amount_of_double_quotes = re.findall( + r"(\"[^\"]+\"?)", selection_text + ) + + if len(amount_of_single_quotes) >= len(amount_of_double_quotes): + selection_text_modified = re.sub( + r"(?:\'([^\']+)\'?)", r'"\1"', selection_text + ) + obj = self.json_loads(selection_text_modified) + self.view.replace(edit, jsonl, self.json_dumps(obj)) + + if selected_entire_file: + self.syntax_to_json() + else: + self.show_exception() + except: + self.show_exception() + + class PrettyJsonAndSortCommand(PrettyJsonCommand, sublime_plugin.TextCommand): - ''' + """ Description: Pretty print json with forced sorting - ''' + """ def run(self, edit): self.force_sorting = True @@ -300,26 +379,23 @@ class PrettyJsonAndSortCommand(PrettyJsonCommand, sublime_plugin.TextCommand): class UnPrettyJsonCommand(PrettyJsonBaseCommand, sublime_plugin.TextCommand): - ''' + """ Description: Compress/minify JSON - it makes json as one-liner - ''' + """ def run(self, edit): self.clear_phantoms() regions = self.view.sel() for region in regions: region, entire_file = self.get_selection_from_region( - region=region, - regions_length=len(region), - view=self.view) + region=region, regions_length=len(region), view=self.view + ) if region is None: continue try: obj = self.json_loads(self.view.substr(region)) - self.view.replace( - edit, region, self.json_dumps(obj=obj, minified=True) - ) + self.view.replace(edit, region, self.json_dumps(obj=obj, minified=True)) if entire_file: self.syntax_to_json() @@ -337,20 +413,20 @@ class JqInsertPrettyJsonCommand(sublime_plugin.TextCommand): class JqPrettyJsonCommand(sublime_plugin.TextCommand): def run(self, edit): - syntax_file = self.view.settings().get('syntax') + syntax_file = self.view.settings().get("syntax") total_region = sublime.Region(0, self.view.size()) content = self.view.substr(total_region) - sublime.run_command('new_window') + sublime.run_command("new_window") preview_window = sublime.active_window() preview_window.run_command( - 'set_layout', + "set_layout", { - 'cols': [0.0, 0.5, 1.0], - 'rows': [0.0, 1.0], - 'cells': [[0, 0, 1, 1], [1, 0, 2, 1]], + "cols": [0.0, 0.5, 1.0], + "rows": [0.0, 1.0], + "cells": [[0, 0, 1, 1], [1, 0, 2, 1]], }, ) @@ -358,13 +434,13 @@ class JqPrettyJsonCommand(sublime_plugin.TextCommand): preview_view = preview_window.new_file() preview_view.set_scratch(True) preview_view.set_read_only(True) - preview_view.set_name('Preview') + preview_view.set_name("Preview") preview_view.sel().clear() preview_window.focus_group(0) jq_view = preview_window.new_file() - jq_view.run_command('jq_insert_pretty_json', {'string': content}) + jq_view.run_command("jq_insert_pretty_json", {"string": content}) jq_view.set_read_only(True) jq_view.set_scratch(True) jq_view.sel().clear() @@ -379,7 +455,7 @@ class JqQueryPrettyJson(sublime_plugin.WindowCommand): """ def is_enabled(self): - settings = sublime.load_settings('Pretty JSON.sublime-settings') + settings = sublime.load_settings("Pretty JSON.sublime-settings") if not self.window: return @@ -388,10 +464,8 @@ class JqQueryPrettyJson(sublime_plugin.WindowCommand): if not view: return - as_json = settings.get('as_json', ['JSON']) - return any( - syntax in view.settings().get('syntax', '') for syntax in as_json - ) + as_json = settings.get("as_json", ["JSON"]) + return any(syntax in view.settings().get("syntax", "") for syntax in as_json) def is_visible(self): return self.is_enabled() @@ -400,19 +474,23 @@ class JqQueryPrettyJson(sublime_plugin.WindowCommand): check_jq() if jq_exists: preview_view = self.window.active_view() - preview_view.run_command('jq_pretty_json') + preview_view.run_command("jq_pretty_json") sublime.active_window().show_input_panel( - 'Enter ./jq filter expression', '.', self.done, self.send_query, None, + "Enter ./jq filter expression", + ".", + self.done, + self.send_query, + None, ) else: sublime.status_message( - './jq tool is not available on your system. http://stedolan.github.io/jq' + "./jq tool is not available on your system. http://stedolan.github.io/jq" ) def get_content(self): - """ returns content of active view or selected region """ + """returns content of active view or selected region""" view = self.window.active_view() - selection = '' + selection = "" regions = view.sel() for region in regions: if region.empty() and len(regions) > 1: @@ -425,14 +503,14 @@ class JqQueryPrettyJson(sublime_plugin.WindowCommand): def send_query(self, query: str): global PREVIOUS_CONTENT, PREVIOUS_QUERY_LEN - settings = sublime.load_settings('Pretty JSON.sublime-settings') + settings = sublime.load_settings("Pretty JSON.sublime-settings") try: p = subprocess.Popen( - [jq_path, query], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - stdin=subprocess.PIPE, - ) + [jq_path, query], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + stdin=subprocess.PIPE, + ) QUERY_LEN = len(query) raw_json = self.get_content() @@ -442,12 +520,12 @@ class JqQueryPrettyJson(sublime_plugin.WindowCommand): if not PREVIOUS_CONTENT[1]: PREVIOUS_CONTENT[1] = raw_json - out, err = p.communicate(bytes(raw_json, 'UTF-8')) - output = out.decode('UTF-8').replace(os.linesep, '\n').strip() - errors = err.decode('UTF-8').replace(os.linesep, '\n').strip() + out, err = p.communicate(bytes(raw_json, "UTF-8")) + output = out.decode("UTF-8").replace(os.linesep, "\n").strip() + errors = err.decode("UTF-8").replace(os.linesep, "\n").strip() jq_view = sublime.active_window().active_view_in_group(1) - if output and output != 'null': + if output and output != "null": if QUERY_LEN > PREVIOUS_QUERY_LEN: PREVIOUS_CONTENT[0] = PREVIOUS_CONTENT[1] PREVIOUS_CONTENT[1] = output @@ -455,14 +533,14 @@ class JqQueryPrettyJson(sublime_plugin.WindowCommand): PREVIOUS_CONTENT[1] = PREVIOUS_CONTENT[0] PREVIOUS_CONTENT[0] = output PREVIOUS_QUERY_LEN = len(query) - elif settings.get('jq_errors', False) and errors: + elif settings.get("jq_errors", False) and errors: output = errors else: if PREVIOUS_QUERY_LEN <= QUERY_LEN: output = PREVIOUS_CONTENT[1] else: output = PREVIOUS_CONTENT[0] - jq_view.run_command('jq_insert_pretty_json', {'string': output}) + jq_view.run_command("jq_insert_pretty_json", {"string": output}) except OSError as ex: sublime.status_message(str(ex)) @@ -473,39 +551,38 @@ class JqQueryPrettyJson(sublime_plugin.WindowCommand): class JsonToXml(PrettyJsonBaseCommand, sublime_plugin.TextCommand): - ''' + """ Description: converts Json to XML - ''' + """ def run(self, edit): - settings = sublime.load_settings('Pretty JSON.sublime-settings') + settings = sublime.load_settings("Pretty JSON.sublime-settings") self.clear_phantoms() regions = self.view.sel() for region in regions: region, entire_file = self.get_selection_from_region( - region=region, - regions_length=len(region), - view=self.view) + region=region, regions_length=len(region), view=self.view + ) if region is None: continue try: h = json.loads(self.view.substr(region)) - root = et.Element('root') + root = et.Element("root") root = self.traverse(root, h) - xml_string = '\n' + xml_string = "\n" - rtn = et.tostring(root, 'utf-8') + rtn = et.tostring(root, "utf-8") if type(rtn) is bytes: - rtn = rtn.decode('utf-8') + rtn = rtn.decode("utf-8") xml_string += rtn if type(xml_string) is bytes: - xml_string = xml_string.decode('utf-8') + xml_string = xml_string.decode("utf-8") - if not entire_file and settings.get('reindent_block', False): + if not entire_file and settings.get("reindent_block", False): xml_string = self.reindent(xml_string, region) self.view.replace(edit, region, xml_string) @@ -517,18 +594,18 @@ class JsonToXml(PrettyJsonBaseCommand, sublime_plugin.TextCommand): self.show_exception(region=region, msg=ex) def traverse(self, element, json_dict): - ''' recursive traverse through dict and build xml tree ''' + """recursive traverse through dict and build xml tree""" if type(json_dict) is dict and json_dict.keys(): for i in json_dict.keys(): e = et.Element(i) element.append(self.traverse(e, json_dict[i])) elif type(json_dict) is list: - e_items = et.Element('items') + e_items = et.Element("items") for i in json_dict: - e_items.append(self.traverse(et.Element('item'), i)) + e_items.append(self.traverse(et.Element("item"), i)) element.append(e_items) else: - element.set('value', str(json_dict)) + element.set("value", str(json_dict)) return element @@ -544,7 +621,7 @@ class PrettyJsonGotoSymbolCommand(PrettyJsonBaseCommand, sublime_plugin.TextComm content = self.view.substr(sublime.Region(0, self.view.size())) try: json_data = self.json_loads(content) - self.generate_items(json_data, '') + self.generate_items(json_data, "") sublime.active_window().show_quick_panel(self.items, self.goto) except Exception as ex: self.show_exception(region=None, msg=ex) @@ -552,14 +629,14 @@ class PrettyJsonGotoSymbolCommand(PrettyJsonBaseCommand, sublime_plugin.TextComm def generate_items(self, json_data, root_key): if isinstance(json_data, OrderedDict): for key in json_data: - new_key_name = f'{root_key}.{key}' + new_key_name = f"{root_key}.{key}" self.items.append(f'"{new_key_name}"') self.goto_items.append(f'"{key}"') self.generate_items(json_data[key], new_key_name) elif isinstance(json_data, list): for index, item in enumerate(json_data): if isinstance(item, str): - self.items.append(f'{root_key}.{item}') + self.items.append(f"{root_key}.{item}") self.goto_items.append(f'"{item}"') def goto(self, pos): @@ -575,8 +652,8 @@ class PrettyJsonGotoSymbolCommand(PrettyJsonBaseCommand, sublime_plugin.TextComm regions = self.view.find_all(string_to_search, sublime.LITERAL) for i, r in enumerate(regions): line = self.view.substr(self.view.full_line(r)) - if ':' in line: - split = line.split(':') + if ":" in line: + split = line.split(":") val = split[1].strip() if string_to_search in val: del regions[i] From 6516ce70701c8fd58694d16bda364324a0ed0940 Mon Sep 17 00:00:00 2001 From: Terminal <32599364+TheSecEng@users.noreply.github.com> Date: Sat, 12 Jun 2021 07:36:41 -0700 Subject: [PATCH 11/12] Update PrettyJson.py Remove print statements --- PrettyJson.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/PrettyJson.py b/PrettyJson.py index f4c6c5a..ec834dd 100644 --- a/PrettyJson.py +++ b/PrettyJson.py @@ -88,14 +88,11 @@ class PrettyJsonBaseCommand: items = [a.strip() for a in content.split(os.linesep)] items = [item[:-1] if item[-1] == "," else item for item in items] replacement = "[" - print(items) for index, item in enumerate(items): if item in ('{', '}'): replacement = replacement + item if item == '}': if index!= len(items)-1: - print(items.index(item)) - print(len(items)-1) replacement = replacement + ',' else: replacement = replacement + item @@ -103,7 +100,6 @@ class PrettyJsonBaseCommand: if items[items.index(item)+1] != '}': replacement = replacement + ',' replacement = replacement + ']' - print(replacement) if len(replacement) <= settings.get("max_arrays_line_length", 120): output_json = output_json.replace(m, replacement, 1) From e17e4588905ab6131040a1f8d3a6e0bc2dba1afd Mon Sep 17 00:00:00 2001 From: TheSecEng Date: Mon, 28 Jun 2021 12:37:22 -0700 Subject: [PATCH 12/12] fix sorting command --- PrettyJson.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/PrettyJson.py b/PrettyJson.py index ec834dd..f2703d7 100644 --- a/PrettyJson.py +++ b/PrettyJson.py @@ -55,11 +55,11 @@ class PrettyJsonBaseCommand: ) @staticmethod - def json_dumps(obj, minified: bool = False) -> str: + def json_dumps(obj, minified: bool = False, force_sorting: bool = False) -> str: settings = sublime.load_settings("Pretty JSON.sublime-settings") sort_keys = settings.get("sort_keys", False) - if PrettyJsonBaseCommand.force_sorting: + if force_sorting: sort_keys = True line_separator = settings.get("line_separator", ",") @@ -270,8 +270,7 @@ class PrettyJsonCommand(PrettyJsonBaseCommand, sublime_plugin.TextCommand): selection_text = self.view.substr(region) try: obj = self.json_loads(selection_text) - - json_text = self.json_dumps(obj=obj, minified=False) + json_text = self.json_dumps(obj=obj, minified=False, force_sorting=self.force_sorting) if not entire_file and settings.get("reindent_block", False): json_text = self.reindent(json_text, region)