如何在 Vim 中保存时自动格式化 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26214156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to auto format JSON on save in Vim
提问by Ali
To be honest gohas spoiled me. With goI got used to having a strict formatting standard that is being enforced by my editor (vim) and is almost accepted and followed by everybody else on the team and around the world.
说实话go已经把我宠坏了。随着go我习惯了严格的格式标准,我的编辑器 (vim) 正在执行该标准,并且几乎被团队中和世界各地的其他所有人接受并遵循。
I wanted to format JSON files on save the same way.
我想以相同的方式在保存时格式化 JSON 文件。
Question: How to auto format/indent/lint json files on save in vim.
问题:如何在 vim 中保存时自动格式化/缩进/lint json 文件。
采纳答案by Ali
Thanks mMontu and Jose B, this is what I ended up doing:
感谢 mmMontu 和 Jose B,这就是我最终要做的:
WARNINGthis will overwrite your buffer. So if you OPEN a json file that already has a syntax error, you will lose your whole file (or can lose it).
警告这将覆盖您的缓冲区。因此,如果您打开一个已经有语法错误的 json 文件,您将丢失整个文件(或者可能会丢失)。
Add this line to your ~/.vimrc
将此行添加到您的 ~/.vimrc
" Ali: to indent json files on save
autocmd FileType json autocmd BufWritePre <buffer> %!python -m json.tool
you need to have python on your machine, of course.
当然,你的机器上需要有python。
EDIT:this next one should not overwrite your buffer if your json has error. Which makes it the correct answer, but since I don't have a good grasp of Vim script or shell for that matter, I present it as an experimental thing that you can try if you are feeling lucky. It may depend on your shell too. You are warned.
编辑:如果您的 json 有错误,下一个不应覆盖您的缓冲区。这使它成为正确的答案,但由于我对 Vim 脚本或 shell 没有很好的掌握,所以我将它作为一个实验性的东西呈现给你,如果你觉得幸运的话,你可以尝试一下。它也可能取决于您的外壳。你被警告了。
" Ali: to indent json files on save
autocmd FileType json autocmd BufWritePre <buffer> %!python -m json.tool 2>/dev/null || echo <buffer>
回答by Jose B
In one command, try this:
在一个命令中,试试这个:
execute '%!python -m json.tool' | w
You could then add you own key binding to make it a simpler keystroke. Of course, for this to work, you need to have Python installed on your machine.
然后,您可以添加自己的键绑定,使其成为更简单的击键。当然,要使其正常工作,您需要在您的机器上安装 Python。
回答by Kyr
If you are keen on using external tool and you are doing some work with json, I would suggest using the jq:
如果您热衷于使用外部工具并且正在使用 json 进行一些工作,我建议您使用jq:
https://stedolan.github.io/jq/
https://stedolan.github.io/jq/
Then, you can execute :%!jq .inside vim which will replace the current buffer with the output of jq.
然后,您可以:%!jq .在 vim 中执行,它将用 jq 的输出替换当前缓冲区。
回答by Pegasus
%!python -m json.tool
%!python -m json.tool
or
或者
%!python -c "import json, sys, collections; print json.dumps(json.load(sys.stdin, object_pairs_hook=collections.OrderedDict), ensure_ascii=False, indent=4)"
%!python -c "import json, sys, collections; print json.dumps(json.load(sys.stdin, object_pairs_hook=collections.OrderedDict), ensure_ascii=False, indent=4)"
you can add this to your vimrc:
你可以把它添加到你的 vimrc 中:
com! FormatJSON %!python -m json.tool
com! FormatJSON %!python -m json.tool
than you can use :FormatJsonformat json files
比您可以使用:FormatJson格式 json 文件
回答by mMontu
A search for JSON plugins on vim.org returned this:
在 vim.org 上搜索 JSON 插件返回了这个:
jdaddy.vim : JSON manipulation and pretty printing
It has the following on description:
它有以下描述:
gqaj"pretty prints" (wraps/indents/sorts keys/otherwise cleans up) the JSON construct under the cursor.
gqaj“漂亮的打印”(包装/缩进/排序键/否则清理)光标下的 JSON 结构。
If it does the formatting you are expecting then you could create an autocmd BufWritePreto format when saving.
如果它符合您期望的格式,那么您可以autocmd BufWritePre在保存时创建一个格式。
回答by Josh Peak
Vim Autoformat
Vim 自动格式化
https://github.com/Chiel92/vim-autoformat
https://github.com/Chiel92/vim-autoformat
There is this Vim plugin which supports multiple auto format and indent schemes as well as extending with custom formatters per filetype.
有这个 Vim 插件,它支持多种自动格式和缩进方案,以及为每个文件类型使用自定义格式化程序进行扩展。
https://github.com/Chiel92/vim-autoformat#default-formatprograms
https://github.com/Chiel92/vim-autoformat#default-formatprograms
Note:
笔记:
You will need to have nodejsand js-beautifyinstalled as vim-autoformatuses these as the default external tool.
你需要有nodejs和js-beautify安装为vim-autoformat使用这些作为默认的外部工具。
npm install -g js-beautify
npm install -g js-beautify
回答by JDS
Here is my solution. It doesn't exactlyaddress the question part of "on save" but if you perform this action before save it will output errors you can then fix before save.
这是我的解决方案。它并没有完全解决“保存时”的问题部分,但是如果您在保存之前执行此操作,它将输出错误,您可以在保存之前修复。
Also, it depends on only one external tool -- jq-- which has become the gold standard of unix shell JSON processing tools. And which you probably already have installed (macOS and Linux/Unix only; idk how this would behave in Windows)
而且,它只依赖于一种外部工具——jq已经成为unix shell JSON处理工具的黄金标准。您可能已经安装了哪些(仅限 macOS 和 Linux/Unix;知道这在 Windows 中的表现如何)
Basically, it's just:
基本上,它只是:
ggVG!jq '.'
That will highlight the entire JSON document then run it through jqwhich will just parse it for correctness, reformat it (e.g. fix any indents, etc), and spit the output back into the Vim editor.
这将突出显示整个 JSON 文档,然后运行它,jq它只会解析它的正确性,重新格式化它(例如修复任何缩进等),并将输出吐回 Vim 编辑器。
If you want to parse only part of the document, you can highlight that part manually by pressing vor Vand then run
如果您只想解析文档的一部分,您可以通过按v或手动突出显示该部分V,然后运行
!jq '.'
The benefit here is that you can fix subsections of your document this way.
这样做的好处是您可以通过这种方式修复文档的小节。
回答by zzuse
you can search for 'vim-json-line-format' plugin, Open a file in Normal mode, move your cursor on the json line, use <leader>pjto show formated json by print it, use <leader>wjcould change the text to formatted json.
Invalid json can not format!
您可以搜索“vim-json-line-format”插件,在 中打开一个文件Normal mode,将光标移动到 json 行上,用于<leader>pj通过打印来显示格式化的 json,使用<leader>wj可以将文本更改为格式化的 json。无效的json无法格式化!

