json.vim (5537B)
1 vim9script 2 3 # Maintainer: Maxim Kim <habamax@gmail.com> 4 # Last update: 2026-09-25 5 # 6 # Set of functions to format/beautify JSON data structures. 7 # 8 # Could be used to reformat a minified json in a buffer (put it into ~/.vim/ftplugin/json.vim): 9 # import autoload 'dist/json.vim' 10 # setl formatexpr=json.FormatExpr() 11 # 12 # Or to get a formatted string out of vim's dict/list/string: 13 # vim9script 14 # import autoload 'dist/json.vim' 15 # echo json.Format({ 16 # "widget": { "debug": "on", "window": { "title": "Sample \"Konfabulator\" Widget", 17 # "name": "main_window", "width": 500, "height": 500 18 # }, 19 # "image": { "src": "Images/Sun.png", "name": "sun1", "hOffset": 250, 20 # "vOffset": 250, "alignment": "center" }, 21 # "text": { "data": "Click Here", "size": 36, "style": "bold", "name": "text1", 22 # "hOffset": 250, "vOffset": 100, "alignment": "center", 23 # "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" } } 24 # }) 25 # 26 # Should output: 27 # { 28 # "widget": { 29 # "debug": "on", 30 # "window": { 31 # "title": "Sample \"Konfabulator\" Widget", 32 # "name": "main_window", 33 # "width": 500, 34 # "height": 500 35 # }, 36 # "image": { 37 # "src": "Images/Sun.png", 38 # "name": "sun1", 39 # "hOffset": 250, 40 # "vOffset": 250, 41 # "alignment": "center" 42 # }, 43 # "text": { 44 # "data": "Click Here", 45 # "size": 36, 46 # "style": "bold", 47 # "name": "text1", 48 # "hOffset": 250, 49 # "vOffset": 100, 50 # "alignment": "center", 51 # "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" 52 # } 53 # } 54 # } 55 # 56 # NOTE: order of `key: value` pairs is not kept. 57 # 58 # You can also use a JSON string instead of vim's dict/list to maintain order: 59 # echo json.Format('{"hello": 1, "world": 2}') 60 # { 61 # "hello": 1, 62 # "world": 2 63 # } 64 65 66 # To be able to reformat with `gq` add following to `~/.vim/ftplugin/json.vim`: 67 # import autoload 'dist/json.vim' 68 # setl formatexpr=json.FormatExpr() 69 export def FormatExpr(): number 70 FormatRange(v:lnum, v:lnum + v:count - 1) 71 return 0 72 enddef 73 74 75 # import autoload 'dist/json.vim' 76 # command -range=% JSONFormat json.FormatRange(<line1>, <line2>) 77 export def FormatRange(line1: number, line2: number) 78 var indent_base = matchstr(getline(line1), '^\s*') 79 80 var [l1, l2] = line1 > line2 ? [line2, line1] : [line1, line2] 81 82 var json_src = getline(l1, l2)->join() 83 var json_fmt = Format(json_src, {use_tabs: !&et, indent: &sw, indent_base: indent_base})->split("\n") 84 85 exe $":{l1},{l2}d" 86 87 if line('$') == 1 && getline(1) == '' 88 setline(l1, json_fmt[0]) 89 append(l1, json_fmt[1 : ]) 90 else 91 append(l1 - 1, json_fmt) 92 endif 93 enddef 94 95 96 # Format JSON string or dict/list as JSON 97 # import autoload 'dist/json.vim' 98 # echo json.Format('{"hello": "world"}', {use_tabs: false, indent: 2, indent_base: 0}) 99 100 # { 101 # "hello": "world" 102 # } 103 104 # echo json.Format({'hello': 'world'}, {use_tabs: false, indent: 2, indent_base: 0}) 105 # { 106 # "hello": "world" 107 # } 108 # 109 # Note, when `obj` is dict, order of the `key: value` pairs might be different: 110 # echo json.Format({'hello': 1, 'world': 2}) 111 # { 112 # "world": 2, 113 # "hello": 1 114 # } 115 export def Format(obj: any, params: dict<any> = {}): string 116 var obj_str = '' 117 if type(obj) == v:t_string 118 obj_str = obj 119 else 120 obj_str = json_encode(obj) 121 endif 122 123 var indent_lvl = 0 124 var indent_base = get(params, "indent_base", "") 125 var indent = get(params, "use_tabs", false) ? "\t" : repeat(' ', get(params, "indent", 2)) 126 var json_line = indent_base 127 var json = "" 128 var state = "" 129 for char in obj_str 130 if state == "" 131 if char =~ '[{\[]' 132 json_line ..= char 133 json ..= json_line .. "\n" 134 indent_lvl += 1 135 json_line = indent_base .. repeat(indent, indent_lvl) 136 elseif char =~ '[}\]]' 137 if json_line !~ '^\s*$' 138 json ..= json_line .. "\n" 139 indent_lvl -= 1 140 if indent_lvl < 0 141 json_line = strpart(indent_base, -indent_lvl * len(indent)) 142 else 143 json_line = indent_base .. repeat(indent, indent_lvl) 144 endif 145 elseif json =~ '[{\[]\n$' 146 json = json[ : -2] 147 json_line = substitute(json_line, '^\s*', '', '') 148 indent_lvl -= 1 149 endif 150 json_line ..= char 151 elseif char == ':' 152 json_line ..= char .. ' ' 153 elseif char == '"' 154 json_line ..= char 155 state = 'QUOTE' 156 elseif char == ',' 157 json_line ..= char 158 json ..= json_line .. "\n" 159 json_line = indent_base .. repeat(indent, indent_lvl) 160 elseif char !~ '\s' 161 json_line ..= char 162 endif 163 elseif state == "QUOTE" 164 json_line ..= char 165 if char == '\' 166 state = "ESCAPE" 167 elseif char == '"' 168 state = "" 169 endif 170 elseif state == "ESCAPE" 171 state = "QUOTE" 172 json_line ..= char 173 else 174 json_line ..= char 175 endif 176 endfor 177 if json_line !~ '^\s*$' 178 json ..= json_line .. "\n" 179 endif 180 return json 181 enddef