-1

How is it possible to get the input of an json file:

       {    "name": "John", 
            "work": "chef", 
            "age": "29", 
            "messages": [
                {
                    "msg_name": "Hello", 
                    "msg": "how_are_you"
                },
                {   "second_msg_name": "hi",
                    "msg": "fine"
                }
            ]
        }

into a Lua table? All json.lua scripts I found did not work for JSON with new lines. Does someone know a solution?

So piglets solution works for the string in the same script. But how does it work with a JSON file?

local json = require("dkjson")

local file = io.open("C:\\Users\\...\\Documents\\Lua_Plugins\\test_file_reader\\test.json", "r")

local myTable = json.decode(file)

print(myTable)

Here then comes the error "bad argument #1 to 'strfind' (string expected, got FILE*)" on. Does someone see my fault?

1
  • you should link the scripts you have tried and how you attempted to use them. another simple solution would be to remove line breaks from the string befor feeding them into your json.lua scripts. but it is probably a user error. any json library should deal with linebreak just fine. Commented Oct 19, 2021 at 15:14

2 Answers 2

3
local json = require("dkjson")
local yourString = [[{    "name": "John", 
        "work": "chef", 
        "age": "29", 
        "messages": [
            {
                "msg_name": "Hello", 
                "msg": "how_are_you"
            },
            {   "second_msg_name": "hi",
                "msg": "fine"
            }
        ]
    }]]
local myTable = json.decode(yourString)

http://dkolf.de/src/dkjson-lua.fsl/home

Sign up to request clarification or add additional context in comments.

4 Comments

If i test this it says "unfinished string near '",'. Did you tested it ? @Piglet
then your string is malformed. my code is ok. edit your question and add how you use the library... you're probably putting that text in quotes which is not ok
i did not know that with the quotes. Now it is working. Do you know an solution with an json file? I will edit my question.
if you use double quotes in your string you need to use something else to make it a string. for example single quotes. but short strings cannot go over multiple lines so you need to use a long literal string as shown in my example. if another question comes up you should post another question. not update your orginal one
1

I found the solution:

local json = require("dkjson")

local file = io.open("C:\\Users\\...\\Documents\\Lua_Plugins\\test_file_reader\\test.json", "r")
local content = file:read "*a"
file:close()
local myTable = json.decode(content)

Comments

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.