You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Neovim Lua中正确写入JSON对象?

解决Neovim插件写入JSON对象的问题

你的问题出在错误地将JSON格式的字符串传给了json_encode,导致它对字符串做了二次编码,最终写入的是转义后的字符串而非JSON对象。

修正后的代码

write = function() 
    -- 直接传入Lua table,而非JSON格式的字符串
    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

关键修正点

  • vim.fn.json_encode的作用是把Lua table转换成JSON格式的字符串,所以参数应该是原生的Lua table(比如{test = "thing"}),而不是已经是JSON结构的字符串。
  • 修正后,json_encode会生成正确的JSON对象字符串{"test": "thing"},写入文件后就是标准的JSON格式。

验证结果

执行修正后的代码,test.json中的内容会是:

{"test": "thing"}

内容的提问来源于stack exchange,提问作者Kooltone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 07:45:34