Check to see if value is in JSON database .

Hello everyone,

I’m having an issue with a JSON database I created. I’ve created a database for zipcodes that looks like this:

[{ "Zipcode": 705, "City": "AIBONITO", "State": "PR" }, { "Zipcode": 36860, "City": "HURTSBORO", "State": "AL" }, { "Zipcode": 91406, "City": "VAN NUYS", "State": "CA" }, { "Zipcode": 610, "City": "ANASCO", "State": "PR" },]

I then call to it using this code

local json = require("json") local fr = io.open(system.pathForFile("ZIPDATABASE.json")) local data = fr:read('\*a') fr:close() data = json.decode(data) local dbtbl = {} local record for i=1, #data do record = data[i] dbtbl[record["Zipcode"]] = { city = record.City, state = record.State } end

I created a text field that people type in there zipcode then it autofills there city and state. My problem is when the zipcode is one that is not in the database it crashes the app. This is the code for the typing in and autofill.

local function zipListener( event ) if ( "began" == event.phase ) then idletime = 0 elseif ( "editing" == event.phase ) then idletime = 0 zipString = event.target.text elseif ( event.phase == "ended" or event.phase == "submitted" ) then idletime = 0 zipString = tonumber(event.target.text) if data[zipString] == nil then local alert = native.showAlert( "Invalid Zip Code", "Zip Code is Invalid.", { "OK" } ) else stateString = dbtbl[zipString].state cityString = dbtbl[zipString].city cityField.text = dbtbl[zipString].city stateField.text = dbtbl[zipString].state end native.setKeyboardFocus( nil ) zipString = event.target.text end

Everything works great except for when the zipcode doesn’t exist. It tries to create 

stateString = dbtbl[zipString].state 

but it cant because the [zipString] isn’t one that’s in the database. I tried to add

if dbtbl[zipString].state == nil then local alert = native.showAlert( "Invalid Zip Code", "Zip Code is Invalid.", { "OK" } ) end

but the app still crashes saying “attempt to index a nil value”. 

My question

Is there a way to check if the string that was written by the user is in the database, then if its not show the “Invalid Zip” alert instead of the app crashing?

Thank you!

-B

Don’t check for nill. Check for the existence.

dbtbl = {} dbtbl[28211] = { city = "charlotte", state = "nc" } print(dbtbl[28211].city) if dbtbl[2323] then print(dbtbl[2323].city) end

Thanks!! I used

 if dbtbl[zipString] then 

and it worked like a charm!

I knew it was something simple.

Don’t check for nill. Check for the existence.

dbtbl = {} dbtbl[28211] = { city = "charlotte", state = "nc" } print(dbtbl[28211].city) if dbtbl[2323] then print(dbtbl[2323].city) end

Thanks!! I used

 if dbtbl[zipString] then 

and it worked like a charm!

I knew it was something simple.