3

I'm trying to write a json file as part of a neovim plugin I'm working on. I started with the code below.

Code:

    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

Output inside test.json: "{\"test\": \"thing\"}"

This almost works, but as you can see it outputs a string. How can I properly get it to write as a JSON object?

1 Answer 1

2

A JSON Object is a string.
https://www.w3schools.com/Js/js_json_objects.asp

The vim.fn.json_encode() is more meant to do things like this...

lua_table = {one = 1, two = 2, three = 3}
json_object = vim.fn.json_encode(lua_table)
-- ^-> '{"one": 1, "two": 2, "three": 3}'

Reference: :help json_encode (nvim command mode)

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()
Sign up to request clarification or add additional context in comments.

1 Comment

FYI: we should use vim.json.encode/decode for better performance power by Lua.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.