Fix issue #32 and issue #30 . adding command to compress/minify json into single line. Added test for it and travis for tests

This commit is contained in:
Nikolajus 2014-04-02 10:55:01 +02:00 committed by Nikolajus Krauklis
parent 1b39fc7052
commit 5d2fad5b62
9 changed files with 86 additions and 19 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
*.pyc *.pyc
*.cache *.cache
*.sublime-project *.sublime-project
.idea

8
.travis.yml Normal file
View File

@ -0,0 +1,8 @@
language: python
python:
- "2.7"
- "3.3"
script:
# Run our tests
- cd tests
- python tests.py

View File

@ -3,6 +3,6 @@
"keys": [ "keys": [
"ctrl+alt+j" "ctrl+alt+j"
], ],
"command": "prettyjson" "command": "pretty_json"
} }
] ]

View File

@ -3,6 +3,6 @@
"keys": [ "keys": [
"super+ctrl+j" "super+ctrl+j"
], ],
"command": "prettyjson" "command": "pretty_json"
} }
] ]

View File

@ -3,6 +3,6 @@
"keys": [ "keys": [
"ctrl+alt+j" "ctrl+alt+j"
], ],
"command": "prettyjson" "command": "pretty_json"
} }
] ]

View File

@ -1,6 +1,10 @@
[ [
{ {
"caption": "Pretty JSON: Reformat (Pretty Print) JSON", "caption": "Pretty JSON: Reformat (Pretty Print) JSON",
"command": "prettyjson" "command": "pretty_json"
},
{
"caption": "Pretty JSON: Minify (compress) JSON",
"command": "un_pretty_json"
} }
] ]

View File

@ -14,10 +14,8 @@ except (ValueError):
s = sublime.load_settings("Pretty JSON.sublime-settings") s = sublime.load_settings("Pretty JSON.sublime-settings")
class PrettyjsonCommand(sublime_plugin.TextCommand): class PrettyJsonCommand(sublime_plugin.TextCommand):
""" Pretty Print JSON """
""" Pretty Print JSON
"""
def run(self, edit): def run(self, edit):
for region in self.view.sel(): for region in self.view.sel():
@ -50,13 +48,49 @@ class PrettyjsonCommand(sublime_plugin.TextCommand):
exc = sys.exc_info()[1] exc = sys.exc_info()[1]
sublime.status_message(str(exc)) sublime.status_message(str(exc))
"""Changes syntax to JSON if its in plain text
"""
def change_syntax(self): def change_syntax(self):
""" Changes syntax to JSON if its in plain text """
if "Plain text" in self.view.settings().get('syntax'): if "Plain text" in self.view.settings().get('syntax'):
self.view.set_syntax_file("Packages/JavaScript/JSON.tmLanguage") self.view.set_syntax_file("Packages/JavaScript/JSON.tmLanguage")
class UnPrettyJsonCommand(PrettyJsonCommand):
"""
Compress/minify JSON
it makes json as one-liner
"""
def run(self, edit):
""" overwriting base class run function to remove intent """
for region in self.view.sel():
selected_entire_file = False
# If no selection, use the entire file as the selection
if region.empty() and s.get("use_entire_file_if_no_selection", True):
selection = sublime.Region(0, self.view.size())
selected_entire_file = True
else:
selection = region
try:
obj = json.loads(self.view.substr(selection),
object_pairs_hook=OrderedDict,
parse_float=decimal.Decimal)
self.view.replace(edit, selection, json.dumps(obj,
ensure_ascii=s.get("ensure_ascii", False),
sort_keys=s.get("sort_keys", False),
separators=(',', ':'),
use_decimal=True))
if selected_entire_file:
self.change_syntax()
except Exception:
import sys
exc = sys.exc_info()[1]
sublime.status_message(str(exc))
def plugin_loaded(): def plugin_loaded():
global s global s
s = sublime.load_settings("Pretty JSON.sublime-settings") s = sublime.load_settings("Pretty JSON.sublime-settings")

View File

@ -1,19 +1,27 @@
Prettify JSON plugin for Sublime Text 2 & 3 Prettify JSON plugin for Sublime Text 2 & 3
## Installation ## Installation
Install this sublime text package via [Package Control](http://wbond.net/sublime_packages/package_control) Install this sublime text package via [Package Control](http://wbond.net/sublime_packages/package_control)
## Usage ## Usage
To prettify JSON, make selection of json and press keys: To prettify JSON, make selection of json and press keys:
- Linux: <kbd>ctrl+alt+j</kbd> - Linux: <kbd>ctrl+alt+j</kbd>
- Windows: <kbd>ctrl+alt+j</kbd> - Windows: <kbd>ctrl+alt+j</kbd>
- OS X: <kbd>cmd+ctrl+j</kbd> - OS X: <kbd>cmd+ctrl+j</kbd>
or through Command Palette <kbd>Ctrl+Shift+P</kbd> find "Pretty JSON: Reformat (Pretty Print) JSON"
If selection is empty and configuration entry **use_entire_file_if_no_selection** is true, tries to prettify whole file. If selection is empty and configuration entry **use_entire_file_if_no_selection** is true, tries to prettify whole file.
If JSON is not valid it will be displayed in status bar of sublime. If JSON is not valid it will be displayed in status bar of sublime.
### Compress / Minify JSON
Using Command Palette <kbd>Ctrl+Shift+P</kbd> find "Pretty JSON: Minify (compress) JSON" this will make selection or full buffer as single line JSON which later you can use in command lines or somewhere else
## Default configuration ## Default configuration
**use_entire_file_if_no_selection** - true **use_entire_file_if_no_selection** - true

View File

@ -1,11 +1,11 @@
try: import sys
# python 3 / Sublime Text 3 import os
from . import simplejson as json
from .simplejson import OrderedDict # parent folder holds libraries which needs to be included
except (ValueError): sys.path.append(os.path.realpath('..'))
# python 2 / Sublime Text 2
import simplejson as json import simplejson as json
from simplejson import OrderedDict from simplejson import OrderedDict
import decimal import decimal
import unittest import unittest
@ -19,7 +19,7 @@ class TestIssues(unittest.TestCase):
def test_ascii_issue_10(self): def test_ascii_issue_10(self):
tmp_str = '{"tempstr":"\u2022"}' tmp_str = '{"tempstr":"\u2022"}'
expected_output = '''{ expected_output = '''{
"tempstr": "\u2022" "tempstr": "\\u2022"
}''' }'''
obj = json.loads(tmp_str, object_pairs_hook=OrderedDict, parse_float=decimal.Decimal) obj = json.loads(tmp_str, object_pairs_hook=OrderedDict, parse_float=decimal.Decimal)
tmp_str = json.dumps(obj, indent=2, ensure_ascii=True, sort_keys=False, tmp_str = json.dumps(obj, indent=2, ensure_ascii=True, sort_keys=False,
@ -67,6 +67,18 @@ class TestIssues(unittest.TestCase):
use_decimal=True) use_decimal=True)
self.assertEqual(tmp_str, expected_output) self.assertEqual(tmp_str, expected_output)
def test_compress_feature(self):
tmp_str = """{
"real": 0.99
}"""
expected_output = '{"real":0.99}'
obj = json.loads(tmp_str, object_pairs_hook=OrderedDict, parse_float=decimal.Decimal)
tmp_str = json.dumps(obj, ensure_ascii=False, sort_keys=False,
separators=(',', ':'),
use_decimal=True)
self.assertEqual(tmp_str, expected_output)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()