vimtricks.wiki Concise Vim tricks, one at a time.

How do I encode and decode JSON data in Vimscript for configuration and plugin development?

Answer

json_encode()

Explanation

Vim 8.0+ and Neovim include built-in json_encode() and json_decode() functions, enabling Vimscript to serialize and parse JSON data without external tools. This is invaluable for plugins that read JSON config files, communicate with language servers, or process CLI output.

How it works

  • json_encode({expr}) — converts a Vim Dict, List, string, or number to a JSON string
  • json_decode({string}) — parses a JSON string and returns the corresponding Vim value

Vim uses special variables for JSON primitives:

  • JSON true / falsev:true / v:false
  • JSON nullv:null
let l:data = {'name': 'Alice', 'scores': [10, 20, 30], 'active': v:true}
let l:json = json_encode(l:data)
" Result: '{"name":"Alice","scores":[10,20,30],"active":true}'
echo l:json

Example

Read and decode a JSON config file:

let l:raw = join(readfile(expand('~/.config/mytool/config.json')), '')
let l:config = json_decode(l:raw)
echo 'Host: ' . l:config.host
echo 'Port: ' . l:config.port

Parse JSON output from a shell command:

let l:raw = system('curl -s https://api.example.com/status')
let l:resp = json_decode(l:raw)
if l:resp.status ==# 'ok'
  echo 'Service is healthy'
endif

Tips

  • json_decode() throws an exception on invalid JSON — wrap in try/catch for robustness
  • Use readfile() (returns a List of lines) with join() to safely read JSON files without shelling out
  • In Neovim Lua, prefer vim.json.encode() / vim.json.decode() for Lua-native code
  • Check for valid JSON before decoding external input: json_decode() is strict (no trailing commas, no comments)
  • For pretty-printing, use python3 -c 'import json,sys; print(json.dumps(json.load(sys.stdin), indent=2))' via system()

Next

How do I use glob() in Vimscript to get a list of files matching a wildcard pattern?