Jump to content
Lunarovich

Read a JSON file into a Lua string / table

Recommended Posts

Hello, I would like to take a JSON file and read its content into a normal Lua string.

 

Even better, I would like to put a JSON text into a Lua table directly, if it's possible.

 

So far, I've found this Lua lib for converting a JSON string into a Lua table and vice versa. However, I don't see how to read a whole file as a string.

 

Thank you in advance!

 

P.S. I know how to read an individual line with this function.

Share this post


Link to post

http://www.leadwerks.com/werkspace/page/api-reference/_/stream/

 

http://www.leadwerks.com/werkspace/page/api-reference/_/filesystem/

 

http://www.leadwerks.com/werkspace/page/api-reference/_/filesystem/filesystemgetappdatapath-r801

 

 

Note that file i/o will not work with the game launcher if you care about that. Also you might have to pay attention of where you are reading/writing the file. I don't think it can be part of the zip file as you won't know the pw to open it. So normally these files need to be somewhere else.

Share this post


Link to post

My question would be why JSON? Is there a specific reason to pick that format?

Share this post


Link to post

Sure! Because that's the format delivered by the third party smile.png

 

Anyway, it does not matter if it's JSON. I just want to read in the string as is and have it in the Lua var.

Share this post


Link to post

Using the example of the API as reference something like the below should do that

 

local stream = FileSystem:ReadFile(path)

if (stream==nil)then Debug:Error("Failed to read file.") end

local json = nil
while (not stream:EOF()) do
json = json..stream:ReadLine
end
stream:Release() 

Share this post


Link to post

Thank you Rick. This is a solution I came up with. It's similar to yours. It puts a JSON string into a Lua table:

 

--Load JSON (http://regex.info/blog/lua/json) library
JSON = (loadfile "lua/JSON.lua")() -- put the lib in "lua" folder
path = "pathToJSON"
stream = FileSystem:OpenFile(path)
jsonString = ""

if (stream) then
while (not stream:EOF()) do
 jsonString = jsonString .. stream:ReadString()
end
data = JSON:decode(Swinglets.jsonString)
else
System:Print("Stream not found")
end

Share this post


Link to post

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...