Efficient way of searching through JSON imported tables

Hi Guys,

let me start by saying that I am having an absolute blast with Corona and coming from XNA I am absolutely amazed how quickly I can prototype something without having to write excessive amount of code.

I have a following question for you guys and I hope you will be able to help.

I dropped SQLite persistence in favor of JSON, for a couple of reasons. I am having some issues with finding a nice, clean way of dynamically retrieving something from a JSON imported table.

Let’s say I have a table called Avatar which basically holds a couple of records about images displayed on the screen (image paths, sizes, offsets etc.). I created a Avatar.lua module with a new() function which is called by another lua file. I want to feed the id (which is a parameter stored in JSON files for each record) into the new method and choose my desired record from the table based on that.

Now in SQLite it’s fairly simple, because the query is a string and I can easily paste something into it, like this:

[lua]local sql = “SELECT * FROM Avatar WHERE id = '”… params.avatar …"’";[/lua]

With JSON it’s not that simple. In most of the tutorials I found, the proposed solution is fixed, static conditionals, like this:

[lua]if(params.avatar == “test1”) then avatar = avatars.test1 end;[/lua]

I don’t want that, because like I said, I want to have it selected dynamically, based solely on what’s stored in JSON files.

The only solution I can think of is iterating through the imported JSON table and checking for each element it’s id property is equal to the fed params.avatar parameter, like this:

[lua]jsonSearch = function(tab, query)
for index,value in ipairs(tab) do
if (value.id == query) then
return value;
end
end
end[/lua]

Is there another way or is it the way to go?

Thanks for any help in advance! [import]uid: 133145 topic_id: 23783 reply_id: 323783[/import]

In your example each field of the table has an index which apparently you don’t use for anything. Why don’t you add elements to that table using that index as the ID?

Let’s assume the IDs are strings. You would have something like:

local table = {  
 ["square"] = {  
 path = "something",  
 width = 47,  
 height = 47  
 },  
 ["circle"] = {  
 path = "somethingElse",  
 width = 46,  
 height = 48  
 }  
}  

So then, when you want an element with a certain ID you simply do:

[code]
local id = “square”

local value = table[id]
[/code] [import]uid: 61899 topic_id: 23783 reply_id: 95772[/import]

Wow, I’ve never realized that you can use node “labels” in JSON as dictionary keys in LUA. That’s a fantastic, thank you very much! [import]uid: 133145 topic_id: 23783 reply_id: 95830[/import]