Skip to content

Instantly share code, notes, and snippets.

@jasonbradley
Created December 15, 2012 05:28
Show Gist options
  • Save jasonbradley/4291520 to your computer and use it in GitHub Desktop.
Save jasonbradley/4291520 to your computer and use it in GitHub Desktop.
Lua read/write data in JSON format
-- load the JSON library.
local Json = require("json")
local JsonStorage = {}
-- Function to save a table.  Since game settings need to be saved from session to session, we will
-- use the Documents Directory
JsonStorage.saveTable = function(t, filename)
local path = system.pathForFile( filename, system.DocumentsDirectory)
local file = io.open(path, "w")
if file then
local contents = Json.encode(t)
file:write( contents )
io.close( file )
return true
else
return false
end
end
JsonStorage.loadTable = function(filename)
local path = system.pathForFile( filename, system.DocumentsDirectory)
local contents = ""
local myTable = {}
local file = io.open( path, "r" )
if file then
-- read all contents of file into a string
local contents = file:read( "*a" )
myTable = Json.decode(contents);
io.close( file )
return myTable
end
return nil
end
return JsonStorage
@NataliaDiaz
Copy link

NataliaDiaz commented Oct 26, 2017

Hi! what library file you use for json.lua? or what luarocks install -json_package- you used? I tried downloading this file https://github.com/rxi/json.lua and also local lfs = require "lfs" with no success. I get attempt to index global 'system' (a nil value)
stack traceback

@hylickipiotr
Copy link

[31]: myTable = Json.decode(contents); you added extra colon.

@vinayak-vc
Copy link

vinayak-vc commented Sep 18, 2019

json.decode does not work for me.


local Jsondata = require("jsonstrorage")
local json = require("json")

local unpack = unpack or table.unpack

function LoadData()

	data = Jsondata.loadTable("jsonfile")
	if data ~= nil then
	print("Not nill")
	end

	print(tostring(json.decode('[1,2,3,{"x":10}]')))

end


LoadData()


I am using this

@vjcalel
Copy link

vjcalel commented Nov 14, 2019

Wrong code for linux. Using system in local function will always reproduce attempt to index global 'system' (a nil value)

@sampixel
Copy link

Because it works on Sola2D game framework i guess (which provide a system.* library)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment