I want to bring an unformatted json and format it with vim for easy viewing.
etc. In the first example, you can display it neatly by using the browser extension, but in the second and third cases, it seems convenient if you can paste it into vim and format it.
In the environment where python2.6 or later is installed (with the python command in the PATH), you can format the json string in the buffer by hitting the following command.
:%!python -m json.tool
For example, if you hit the above command when such a string is in the buffer
{"count":1,"list":[{"url":"http://json.org/example.html","title":"\u3042\u3044\u3046\u3048\u304a"}]}
I feel like this.
{
"count": 1,
"list": [
{
"title": "\u3042\u3044\u3046\u3048\u304a",
"url": "http://json.org/example.html"
}
]
}
It feels good. However, I'm not very happy with the Japanese being escaped (I'm also worried about the half-width space at the end of the line). So, I made a slightly improved command. I'm new to vim, so I'd be happy if you could get me a tsukkomi.
command! JsonFormat :execute '%!python -m json.tool'
\ | :execute '%!python -c "import re,sys;chr=__builtins__.__dict__.get(\"unichr\", chr);sys.stdout.write(re.sub(r\"\\u[0-9a-f]{4}\", lambda x: chr(int(\"0x\" + x.group(0)[2:], 16)), sys.stdin.read()))"'
\ | :%s/ \+$//ge
\ | :set ft=javascript
\ | :1
If you write a brief explanation
When you execute the command
:JsonFormat
The display will be as follows.
{
"count": 1,
"list": [
{
"title": "AIUEO",
"url": "http://json.org/example.html"
}
]
}
Recommended Posts