I’m following the instructions on this page:
http://www.coronalabs.com/blog/2011/08/03/tutorial-exploring-json-usage-in-corona/
Here’s the sample.json I’ve saved to my simulator:
{
"name": "Jack (\"Bee\") Nimble",
"format": {
"shape": "rect",
"width": 1920,
"height": 1080,
"interlace": false,
"framerate": 24
}
}
And I’ve got this going in my main.lua:
require "json"
-- jsonFile() loads json file & returns contents as a string
local jsonFile = function( filename, base )
if not base then base = system.ResourceDirectory; end -- set default base dir if none specified
local path = system.pathForFile( filename, base ) -- create a file path for corona i/o
local contents -- will hold contents of file
-- io.open opens a file at path. returns nil if no file found
local file = io.open( path, "r" )
if file then
-- read all contents of file into a string
contents = file:read( "\*a" )
io.close( file ) -- close the file after using it
end
return contents
end
local t = json.decode( jsonFile( "sample.json" ) )
print(#t); --\> returns 0
print(t.name); --\> Jack ("Bee") Nimble
print(t.format.shape); --\> rect
So this works, as described! Hurray!
But I’m trying to understand more complicated JSON files.
And Here’s an example of a JSON file I created and I’m attempting to parse:
(I do get the feeling I’m formatting it incorrectly)
{
{ "firstname": "Jack", "lastname": "Black" },
{ "firstname": "Jose", "lastname": "Ringo" },
{ "firstname": "Janet", "lastname": "Macky" },
{ "firstname": "Jones", "lastname": "Potter" }
}
I’m putting tables within the primary table, and I wish to parse it.
local myTable = json.decode( jsonFile( "sample.json" ) )
for i=1,#myTable do
print( myTable[i][firstname] )
end
I’m getting a error pointing to the json.decode() section. I’m sure it’s a parsing issue, but I’m stuck. [import]uid: 154122 topic_id: 28176 reply_id: 328176[/import]