json.decodeFile()

Type Function
Library json.*
Return value Table
Revision Current Public Release (2017.3068)
Keywords json
See also json.decode()

Overview

Decodes the contents of a file that is expected to contain JSON-encoded data and returns a Lua object (table) with the appropriate data. The return value is a Lua object when the data is successfully decoded or, in the case of an error, three values: nil, the position of the next character that doesn't belong to the object, and an error message. Errors can either relate to issues opening the file or to JSON syntax issues.

Gotchas

The filename parameter should usually be obtained from system.pathForFile() so it can be correctly located in the application's sandbox. See the Example below.

Syntax

json.decodeFile( filename [, position [, nullval]] )
filename (required)

String. String containing the name of a file containing JSON data.

position (optional)

Number. Index within file to start decoding (default is 1 if omitted).

nullval (optional)

Value to be returned for items with a value of json.null (see json.encode()). This is useful if your data contains items which are "null" but you need to know of their existence (in Lua, table items with values of nil don't normally exist).

Example

local json = require( "json" )

local filename = system.pathForFile( "datafile.json", system.ResourceDirectory )
local decoded, pos, msg = json.decodeFile( filename )

if not decoded then
    print( "Decode failed at "..tostring(pos)..": "..tostring(msg) )
else
    print( "File successfully decoded!" )
end