如何在 Neovim Lua 中编写 JSON?

3
我正在尝试编写一个json文件,作为我正在开发的neovim插件的一部分。我从下面的代码开始。
代码:
    write = function() 
        local json = vim.fn.json_encode("{\"test\": \"thing\"}")
        print(json)
        local ok, result = pcall(vim.fn.writefile, {json}, "./test.json")

        if ok then
            print("Okay")
        else
            print(result)
        end
    end

在test.json内输出: "{\"test\": \"thing\"}"

这个方法基本可行,但是它输出的是一个字符串。如何正确地将其写入JSON对象?

1个回答

2
一个JSON对象是一个字符串。
https://www.w3schools.com/Js/js_json_objects.asp vim.fn.json_encode() 更适合做这样的事情...
lua_table = {one = 1, two = 2, three = 3}
json_object = vim.fn.json_encode(lua_table)
-- ^-> '{"one": 1, "two": 2, "three": 3}'

参考::help json_encode(nvim 命令模式)
json_encode({expr})                                     json_encode()
                Convert {expr} into a JSON string.  Accepts
                msgpack-special-dict as the input.  Will not convert
                Funcrefs, mappings with non-string keys (can be created as
                msgpack-special-dict), values with self-referencing
                containers, strings which contain non-UTF-8 characters,
                pseudo-UTF-8 strings which contain codepoints reserved for
                surrogate pairs (such strings are not valid UTF-8 strings).
                Non-printable characters are converted into "\u1234" escapes
                or special escapes like "\t", other are dumped as-is.
                Blobs are converted to arrays of the individual bytes.

                Can also be used as a method:
                        GetObject()->json_encode()

FYI:我们应该使用由Lua提供支持的vim.json.encode/decode以获得更好的性能。 - VimNing

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接