Code Monkey home page Code Monkey logo

sublimeprettyjson's Introduction

Pretty Json Tests

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 search for package: "Pretty JSON"

Manual Installation

Sublime Text 4

  • cd <Packages directory> (MacOS: ~/Library/Application\ Support/Sublime\ Text/Packages)
  • git clone https://github.com/dzhibas/SublimePrettyJson.git "Pretty JSON"

Sublime Text 3

  • cd <Packages directory> (MacOS: ~/Library/Application\ Support/Sublime\ Text\ 3/Packages)
  • git clone https://github.com/dzhibas/SublimePrettyJson.git "Pretty JSON"
  • cd Pretty JSON
  • git checkout st3

Sublime Text 2 No longer supported

Usage

To prettify JSON, make selection of json (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')

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 Text

Validate JSON

Using Command Palette Ctrl+Shift+P find "Pretty JSON: Validate" (you can search for partial string 'validate') this will validate selection or full file and will show in dialog if it's valid or invalid. In case of found errors view will jump to error and will highlight it

Compress / Minify JSON

Using Command Palette Ctrl+Shift+P find "Pretty JSON: Minify JSON" (you can search for part of it like 'json minify') this will make selection or full buffer as single line JSON which later you can use in command lines (curl/httpie) or somewhere else...

To map a key combination like Ctrl+Alt+M to the Minify command, you can add a setting like this to your .sublime-keymap file (eg: Packages/User/Default (Windows).sublime-keymap):

  { "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 "Pretty JSON: json2xml" (you can search for part of it like '2XML') this will convert your selected JSON of full buffer to XML and replace syntax and buffer to XML output

./jQ query/filter usage

Demo:

Demo

If on your machine "./jq" tool is available with ctrl+atl+shift+j you can run against your json. output will be opened in new view so you can once again apply jq on new buffer

You can find instructions of tool here:

http://stedolan.github.io/jq/

Configuration

Check all the available configuration keys and their default values by using the Command Palette Ctrl+Shift+P and searching for Preferences: Pretty JSON Settings. From there you can also configure your own values.

Here's a run down of the existing parameters, their meaning, and how you can configure each of them:

  • use_entire_file_if_no_selection: boolean that indicates whether the entire file should be used when there is no text selected.

  • indent: integer that represents the number of spaces to be used. To use tab indentation, use \t instead.

  • sort_keys: boolean that indicates whether the JSON keys should be sorted alphabetically.

  • ensure_ascii: boolean that indicaes whether it should validate that all characters are ASCII characters.

  • line_separator: string that represents the separator that will be used between lines. Usually this shouldn't be modified, to make sure the resulting JSON is valid.

  • value_separator: string that represents the separator that will be used between JSON keys and values. If you need to get rid of extra space after the collon, you can configure that using this parameter.

  • keep_arrays_single_line: boolean that indicates whether we need to re-structure arrays and make them single-line.

  • max_arrays_line_length: integer that determines the max length of single-line values. When the line exceeds this max length, it will be formatted in a multi-line fashion.

  • pretty_on_save: boolean that indicates whether JSON files should be automatically prettified on each file save.

  • validate_on_save: boolean that indicates whether JSON files should be automatically validated on each file save.

  • brace_newline: boolean that indicates whether there should be a newline after braces.

  • bracket_newline: boolean that indicates whether there should be a newline after brackets. true here means the resulting JSON will look like the Allman indentation style, while false will result in an OTBS indentation style.

  • reindent_block: if we are formatting a selection, if we need to reindent the resulting block to follow the flow of the source document the posible values are minimal and start.

    Using minimal the resulting json lines are indented as much spaces as theline where the selection starts. E.g.:

    yaml_container:
    yaml_key: { "json": "value" }

    Gets formatted as:

    yaml_container:
        yaml_key: {
          "json": "value"
        }

    Using start, the resulting json lines are indented a number of spaces equal to the column number of the start of the selection. With start the previous example gets formatted as:

    yaml_container:
        yaml_key: {
                    "json": "value"
                  }

    Use false if you wouldn't like the formatter to reindent the block at all.

  • jq_binary: path to the jq binary, e.g. /usr/bin/local/jq.

Using tabs for indentation

You can change configuration key indent to string value "\t" or any other string

"indent" : "\t",

Be sure "Indent Using Spaces" is unchecked otherwise you will not see effect and ST3/4 will convert it back to spaces

Contributors

Others

If you YAMLing then maybe you interested in this plugin: PrettyYAML

sublimeprettyjson's People

Contributors

crcastle avatar deathaxe avatar dzhibas avatar frewsxcv avatar grenade avatar grossbart avatar jonnolen avatar kuttkatrea avatar mrliaocn avatar pradeephrish avatar rchl avatar rogerluan avatar seldaek avatar sharunkumar avatar silwing avatar tadashi-aikawa avatar terminalfi avatar the3rdhbtaylor avatar tolgamorf avatar yukixz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sublimeprettyjson's Issues

Suggestion: Automatically switch syntax coloring to JSON

My common approach is, open a new file, paste in some JSON, use your great plugin to prettify. But Sublime still uses Plain text syntax coloring. It would be great if the plugin could switch the syntax coloring after it runs.

This probably should only apply to the "Whole File" option.

Convert JSON to csv

json to hash, hash to csv

you can even re-format json with ./jq to your own format and then convert to csv and save

UnicodeEncodeError

When I use the jq function in Windows 10, I get the following error:

image

When I change the code in line 200

out, err = p.communicate(bytes(raw_json))

to

out, err = p.communicate(raw_json.encode('utf-8'))

, it works.

Hope it helps. Or maybe another better solution.

Enable single-line declarations

I'm not sure this is a feature you'd want to support (should of course be configurable), but I'll raise it.

I'm in the process of writing a large json-schema file, now almost a 1000 line long and it will grow even more.

I'd want to have the ability to have one-liners where possible.

For example, instead of having this:

"description": {
      "$ref": "http://json-schema.org/draft-04/schema#/properties/description"
}

I'd hope to see this:

"description": { "$ref": "http://json-schema.org/draft-04/schema#/properties/description" }

I have plenty one-liner objects (mostly json references) and it would really compress the json and make it more readable (in my opinion at least).

I would love to see a similar option for arrays of primitives, though that's less important.
This means that this:

"enum": [
        "csv",
        "ssv",
        "tsv",
        "pipes",
        "multi"
]

would become this:

"enum": [ "csv", "ssv", "tsv", "pipes", "multi" ]

I understand that this may be an issue even with primitives as string values (and numbers for that matter) can end up having pretty long values.

ST3 Error

reloading plugin SublimePrettyJson.PrettyJson
Traceback (most recent call last):
File "D:\Programs\Sublime Text 3\sublime_plugin.py", line 70, in reload_plugin
m = importlib.import_module(modulename)
File "X/importlib/init.py", line 88, in import_module
File "", line 1577, in _gcd_import
File "", line 1558, in _find_and_load
File "", line 1525, in _find_and_load_unlocked
File "", line 586, in _check_name_wrapper
File "", line 1023, in load_module
File "", line 1004, in load_module
File "", line 562, in module_for_loader_wrapper
File "", line 854, in _load_module
File "", line 981, in get_code
File "", line 313, in _call_with_frames_removed
File "D:\Users\Me\AppData\Roaming\Sublime Text 3\Packages\SublimePrettyJson\PrettyJson.py", line 41
except Exception, e:
^
SyntaxError: invalid syntax
found 4 files for base name Default.sublime-keymap
found 3 files for base name Main.sublime-menu

json 2 xml

Convert JSON to hash and from hash to XML.

If text is separeted by Enter (return key) the command doesn't work

Let's say that you have
{"random":"0.91780721000395720.39120557019487023","pass":true}

If you paste this in sb2 and hit ctrl alt j it works. If you hit enter and paste it again it doesn't. I tried different combination and sometimes it doesn't work when you paste it one after the other, with nothing selected. If I select the second data pasted in and hit ctrl alt j it works. So the problems seems to be when nothing is selected.

Thanks for this great package. Please tell me if I didn't explain correctly.

Sort object alphabetically by keys

A lot of times, I want to have an object sorted alphabetically by keys just to help me read it better. Specifically, this applies to package.json and manifest.json files. I wonder if it would be too hard to implement an option that does that as part of this package?

Changes encoded characters to ascii - no option

There's no option to keep encoded characters such as "\u2022". I have json files that, for what they're being used for, need to keep those characters encoded, so the prettifier can't be used.

Does not work in build 2221

I don't know what is the cause, but I cannot properly install this package from Package Control. After install there is nothing that changed in the editor: no custom settings menu item, Ctrl+Alt+J doesn't work, no new items in the Command Palette.
Files appear to be properly placed in the Packages folder. Also no errors in console.
My version of Sublime Text is 2.0.2, build 2221, used on Windows 8.

./jq doesnt work on windows

Try to use ./jq module of ur plugin and it said that "jq tool is not available on your system". But i now that it is. But what more interesting - it works early in 2014. Try to analyse your sources and find that this code

s = subprocess.Popen(["jq", "--version"],
                         stderr=subprocess.PIPE,
                         stdout=subprocess.PIPE)

calls an error "WinError6"
And find this python issue report

And it solves a problem in my case:

s = subprocess.Popen(["jq", "--version"],
                         stdin=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         stdout=subprocess.PIPE)

Jump to

would be nice to specify ./jQ path and jump to that point in json structure

Un-Pretty JSON

Any chance of extending this bad boy to convert prettied JSON into a single string?

jq and code folding

hey Nikolajus, awesome plugin, congrats. am having a couple issues though:

first, I am trying to use jq but i get the message "jq tool is not available on your system" although but i do have it:

bash-3.2$ jq --version
jq version 1.3

i looked at the code at PrettyJson.py and it should be working, but not sure what might be going on. I pasted my console output at the bottom of this message

Second, I saw #29 and am having the same problem, but I am using sublime text 3 and still can't get the json code to fold.

here is the output from the console:

tartup, version: 3059 osx x64 channel: stable
executable: /Applications/Sublime Text.app/Contents/MacOS/Sublime Text
working dir: /
packages path: /Users/rpietro/Library/Application Support/Sublime Text 3/Packages
state path: /Users/rpietro/Library/Application Support/Sublime Text 3/Local
hardware concurrency: 4
zip path: /Applications/Sublime Text.app/Contents/MacOS/Packages
zip path: /Users/rpietro/Library/Application Support/Sublime Text 3/Installed Packages
found 27 files for base name Default.sublime-keymap
found 3 files for base name Default.sublime-mousemap
found 21 files for base name Main.sublime-menu
top level value must be an array
loading bindings
loading pointer bindings
found 1 files for base name Soda Dark.sublime-theme
theme loaded
app ready
wrote startup cache, added files: 1 orphaned files: 5 total files: 349 cache hits: 348
pre session restore time: 0.212043
using gamma: 2 (err: 6.9282)
first paint time: 0.272535
startup time: 0.296591
launching: /Applications/Sublime Text.app/Contents/MacOS/plugin_host
reloading plugin Default.block
reloading plugin Default.comment
reloading plugin Default.copy_path
reloading plugin Default.delete_word
reloading plugin Default.detect_indentation
reloading plugin Default.duplicate_line
reloading plugin Default.echo
reloading plugin Default.exec
reloading plugin Default.fold
reloading plugin Default.font
reloading plugin Default.goto_line
reloading plugin Default.history_list
reloading plugin Default.indentation
reloading plugin Default.kill_ring
reloading plugin Default.mark
reloading plugin Default.new_templates
reloading plugin Default.open_file_settings
reloading plugin Default.open_in_browser
reloading plugin Default.pane
reloading plugin Default.paragraph
reloading plugin Default.paste_from_history
reloading plugin Default.save_on_focus_lost
reloading plugin Default.scroll
reloading plugin Default.set_unsaved_view_name
reloading plugin Default.side_bar
reloading plugin Default.sort
reloading plugin Default.swap_line
reloading plugin Default.switch_file
reloading plugin Default.symbol
reloading plugin Default.transform
reloading plugin Default.transpose
reloading plugin Default.trim_trailing_white_space
reloading plugin CSS.css_completions
reloading plugin Diff.diff
reloading plugin HTML.encode_html_entities
reloading plugin HTML.html_completions
reloading plugin AutoSelect.autoselect
reloading plugin Better Completion.main
reloading plugin ColorPicker.sublimecp
reloading plugin Emmet.emmet-plugin
reloading plugin Gist.gist
reloading plugin Git.add
reloading plugin Git.annotate
reloading plugin Git.commit
reloading plugin Git.diff
reloading plugin Git.flow
reloading plugin Git.git
reloading plugin Git.history
reloading plugin Git.repo
reloading plugin Git.stash
reloading plugin Git.status
reloading plugin Git.statusbar
reloading plugin GitHubinator.githubinator
reloading plugin JSON Reindent.json_reindent
reloading plugin JsonTree.JsonTree
reloading plugin Open URL.example
reloading plugin Open URL.open_url
reloading plugin Origami.origami
loaded 839 snippets
reloading plugin Package Control.Package Control
reloading plugin PersistentRegexHighlight.PersistentRegexHighlight
reloading plugin Pretty JSON.PrettyJson
reloading plugin RegReplace.rr_plugin
reloading plugin RegReplace.rr_replacer
reloading plugin RegReplace.rr_sequencer
reloading plugin Select By Regex.SelectByRegexCommand
reloading plugin SelectUntil.edit
reloading plugin SelectUntil.select-until
reloading plugin SendText.SendText
reloading plugin Simple Print Function.SublimePrint
reloading plugin SmartMarkdown.headline
reloading plugin SmartMarkdown.headline_level
reloading plugin SmartMarkdown.headline_move
reloading plugin SmartMarkdown.pandoc_render
reloading plugin SmartMarkdown.smart_folding
reloading plugin SmartMarkdown.smart_list
reloading plugin SmartMarkdown.smart_table
reloading plugin SmartMarkdown.table
reloading plugin SmartMarkdown.utilities
reloading plugin Table Editor.table_base
reloading plugin Table Editor.table_border_syntax
reloading plugin Table Editor.table_emacs_org_mode_syntax
reloading plugin Table Editor.table_lib
reloading plugin Table Editor.table_lib_test
reloading plugin Table Editor.table_line_parser
reloading plugin Table Editor.table_multi_markdown_syntax
reloading plugin Table Editor.table_pandoc_syntax
reloading plugin Table Editor.table_plugin
reloading plugin Table Editor.table_plugin_test
reloading plugin Table Editor.table_re_structured_text_syntax
reloading plugin Table Editor.table_simple_syntax
reloading plugin Table Editor.table_textile_syntax
reloading plugin Table Editor.widechar_support
reloading plugin TrailingSpaces.trailing_spaces
reloading plugin Trello.card_options
reloading plugin Trello.custom_actions
reloading plugin Trello.executable
reloading plugin Trello.open_views
reloading plugin Trello.operations
reloading plugin Trello.output
reloading plugin Trello.progress_notifier
reloading plugin Trello.test_harness
Install the AAAPT Package to test Trello from SublimeText
reloading plugin Trello.trello
reloading plugin Trello.trello_collection
reloading plugin Trello.trello_delete_cache
reloading plugin Trello.trello_navigate
reloading plugin Trello.trello_notifications
reloading plugin Trello.trello_reload
reloading plugin WordCount.WordCount
reloading plugin xml2json.Xml2json
reloading plugin xml2json.xmltodict
reloading plugin YAML Nav.yaml_nav
reloading plugin Pretty YAML.PrettyYaml
reloading plugin SublimeCodeIntel.SublimeCodeIntel
plugins loaded
Emmet: No need to update PyV8
Package Control: Skipping automatic upgrade, last run at 2014-05-31 19:54:11, next run at 2014-05-31 20:54:11 or after

Support non-quoted JSON keys

We often have a "JSON" dump with unquoted keys. It would be great if the prettifier would handle this JSON and not require quoted keys.

Run specific jq queries

I'd like to be able to run specific jq queries automatically, maybe via specifying a custom key binding such as

{
"keys": ["super+shift+q"],
"command": "jq_pretty_json",
"args": {"query": "myquery"}
},

but currently the run() method doesn't seem to allow any extra args. Can it be done?

Thanks! :)

Highlight error on json parse exception

Capture exception and together with showing exception message in status bar, also highlight line in which error happened

demo code:

       try:
            # parse part
        except ValueError:
            message = str(sys.exc_info()[1])
            matcher = re.compile('line (\d+) column')
            m = self.matcher.search(message)
            if m:
                row = int(m.group(1)) - 1
                regions = [view.full_line(view.text_point(row, 0)), ]
                view.add_regions('json', regions, 'invalid', 'dot', sublime.DRAW_OUTLINED)

Doesn't work on Mac

I don't know what the "super" key is, but I assume it's command. I installed via package manager, pressed command-ctrl-j and nothing happens.

Enhancements?

I really like this Sublime Package! Thanks for putting it together. There were a few things I thought it would be nice to add. Instead of just asking you to add them, I went ahead and patch a clone of your repository to add them. If you want, I can provide you with a patch so you can determine if you want to add any or all of the functionality.

Here is a list of the changes I made:

  1. Allow it to process the entire file if there is no selection
  2. Changed the keymap entries to only execute in the source.json scope
  3. Added sublime-settings to control the "process entire file if there is no selection", "sort_keys", and "indent_size"
  4. Added a Main.sublime-menu so that the default and user settings files are accessible via the Preferences menu
    Added a Default.sublime-commands to surface the prettyjson command via the Command Palette.

If you would like the patch that I created, please let me know.

Thanks,

H.B. Taylor

Pretty print should set syntax json

When doing pretty print json it should automatically set syntax json. It can be a user option if everybody doesn't want it enabled by default.

./jq under Linux does not work

Console gives this during launch of ST:

reloading plugin Pretty JSON.PrettyJson
[Errno 2] No such file or directory: 'jq'

But it's very much installed, and in my path:

nostr@damus:~$ jq --version
jq version 1.3

Sidenote

Trying to figure this out I upgraded jq to 1.4, which changes the version output to:

nostr@damus:~$ jq --version
jq-1.4

...which probably means that your parsing of the version number doesn't work anymore. Just a heads-up.

JSON Validation

Need a function to check if selected json or opened file is valid or not

Minify JSON too

It would be nice to have a minify/beautify toggle instead of only beautify.

Is it hard to implement?

support for c style comments

I know it's not something that is officially on www.json.org but it's a fairly common extension and many parsers allow comments and it would be nice if pretty json would allow them, too :)

maybe it could simply ignore stuff between /* */ ?

Option for keeping long arrays on a single line when prettifying

Hey there

Would it be possible to have an option to keep long arrays on a single line when prettifying a JSON?

I work a lot with large JSON files that contain 3D geometries like vertices, faces, etc. that are stored in large arrays. When prettifying those it puts all the array elements on an individual line.
It would be great to have an option to just keep arrays as they are and prettify everything else.

Unfortunately I don't know much about Sublime Packages and how PrettyJson works under the hoods, but if it's possible I can look into it and make a pull request.

Cheers,
Sandro

Needs a menu item

I'm not going to remember the keybinding for this in a few days -- I need it to be in the tools menu. Can you add a menu item or document how it's done? Thanks!

Missing License

There doesn't appear to be a license, can you please add one? MIT :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.