json.lua (2628B)
1 ---@meta 2 3 ---@nodoc 4 vim.json = {} 5 6 -- luacheck: no unused args 7 8 --- @class vim.json.decode.Opts 9 --- @inlinedoc 10 --- 11 --- Convert `null` in JSON objects and/or arrays to Lua `nil` instead of |vim.NIL|. 12 --- (default: `nil`) 13 --- @field luanil? { object?: boolean, array?: boolean } 14 --- 15 --- Allows JavaScript-style comments within JSON data. Comments are treated as whitespace and may 16 --- appear anywhere whitespace is valid in JSON. Supports single-line comments beginning with '//' 17 --- and block comments enclosed with '/*' and '*/'. 18 --- (default: `false`) 19 --- @field skip_comments? boolean 20 21 --- @class vim.json.encode.Opts 22 --- @inlinedoc 23 --- 24 --- Escape slash characters "/" in string values. 25 --- (default: `false`) 26 --- @field escape_slash? boolean 27 --- 28 --- If non-empty, the returned JSON is formatted with newlines and whitespace, where `indent` 29 --- defines the whitespace at each nesting level. 30 --- (default: `""`) 31 --- @field indent? string 32 --- 33 --- Sort object keys in alphabetical order. 34 --- (default: `false`) 35 --- @field sort_keys? boolean 36 37 ---@brief 38 --- 39 --- This module provides encoding and decoding of Lua objects to and 40 --- from JSON-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|. 41 42 --- Decodes (or "unpacks") stringified JSON to a Lua object. 43 --- 44 --- - Decodes JSON "null" as |vim.NIL| (controllable by {opts}, see below). 45 --- - Decodes empty object as |vim.empty_dict()|. 46 --- - Decodes empty array as `{}` (empty Lua table). 47 --- 48 --- Example: 49 --- 50 --- ```lua 51 --- vim.print(vim.json.decode('{"bar":[],"foo":{},"zub":null}')) 52 --- -- { bar = {}, foo = vim.empty_dict(), zub = vim.NIL } 53 --- ``` 54 --- 55 ---@param str string Stringified JSON data. 56 ---@param opts? vim.json.decode.Opts 57 ---@return any 58 function vim.json.decode(str, opts) end 59 60 --- Encodes (or "packs") a Lua object to stringified JSON. 61 --- 62 --- Example: Implement a basic 'formatexpr' for JSON, so |gq| with a motion formats JSON in 63 --- a buffer. (The motion must operate on a valid JSON object.) 64 --- 65 --- ```lua 66 --- function _G.fmt_json() 67 --- local indent = vim.bo.expandtab and (' '):rep(vim.o.shiftwidth) or '\t' 68 --- local lines = vim.api.nvim_buf_get_lines(0, vim.v.lnum - 1, vim.v.lnum + vim.v.count - 1, true) 69 --- local o = vim.json.decode(table.concat(lines, '\n')) 70 --- local stringified = vim.json.encode(o, { indent = indent, sort_keys = true }) 71 --- lines = vim.split(stringified, '\n') 72 --- vim.api.nvim_buf_set_lines(0, vim.v.lnum - 1, vim.v.count, true, lines) 73 --- end 74 --- vim.o.formatexpr = 'v:lua.fmt_json()' 75 --- ``` 76 --- 77 ---@param obj any 78 ---@param opts? vim.json.encode.Opts 79 ---@return string 80 function vim.json.encode(obj, opts) end