Parsing API data

Hey everyone. I have some code that requests information from an api server that returns a json table.

local function handleResponse( event ) if not event.isError then local response = json.decode( event.response ) print( event.response ) print (response.eventname) print ("finished api call") else print( "Error" ) end return end network.request( "MY\_URL\_HERE", "GET", handleResponse)

The problem I’m having is that I can’t access the code outside of the handleResponse function. I’ve tried returning response as well as making response global before I assign its value. The print statements print what they should, but if I try to do something outside the function, it doesn’t work. I either get a response that the table is nil or that it is userdata. Any guidance as to how to manage this data? Let me know if you need more information.

Thanks in advance!

In the code you provided response is local to the callback and will be nil when the callback completes.

You will need to scope a reference (external to the callback) to store the JSON.

You can then parse it at a later date.

Hi,

I have a prepared a callback snippet & you can use this single server.lua module for number of api methods.

Just require the server.lua in main.lua globally & use it everywhere u want the api data ith respective calback.

SERVER API  LUA MODULE

[lua]

–server.lua

local server={}

local json = require (“json”)

—=======================================Variable=========================

local headers={}

local params = {}

params.headers = headers

headers[“Content-Type”] = “application/json”

local callbackFunction

local basrUrl=“http://assif.com/

–======================Common Network  Listener===========================
 

local commonNtwrkListener =function( event )    

    if ( event.isError ) then

        print(event.isError )

        local alert = native.showAlert( “Network Error”,“Please try again.”, { “OK”})

        

    else

       --print ( "networkListener RESPONSE: " …json.prettify(event.response))

        local data = json.decode( event.response )   

        if(callbackFunction~=nil) then 

         callbackFunction(data)

        end        

    end

end

–============================API METHODS====================================

function server:fetchUserData(callback)

    callbackFunction=callback

    network.request( basrUrl…“apiMethodName”, “GET”, commonNtwrkListener, params )   

end

function server:checkUserdata(callback,dataArr)

    callbackFunction=callback

    params.body=json.encode (data)    

    network.request( basrUrl…“apiMethodName”, “POST”, commonNtwrkListener, params )   

end

-----============================================================
 

return server

[/lua]

MAIN.LUA 

[lua]

–main.lua

local server = require(“server”)


local checkUserDataCallback = function (data)

– Use Data Here…

end

 local dataArr ={name=“Assif”,pswd=“12345”}

 server:checkUserdata(checkUserDataCallback,dataArr)    


local fetchUserDataCallback = function (data)

– Use Data Here…

end

 server:fetchUserData(fetchUserDataCallback)    

[/lua]

  • Assif

Thanks for all the help!

welcome

@assif, apart from over complicating a simple network request you haven’t addressed the scoping issue of the callback being local - which was the OP problem.

Anyway, this will cure your issues (with a lot less code)

local storedData = nil local function handleResponse( event ) if not event.isError and event.response then storedData = json.decode( event.response ) end end network.request( "MY\_URL\_HERE", "GET", handleResponse) ... then later on (this does depend on the JSON returned) local value1 = storedData.value1 local value2 = storedData.value2

@spehere games

As per my snippet, the callback will be always local, being called from any of the Lua files as required.

I have kept listener, callbacks possibly local in its module.

The only thing is I have to return the reference of server.lua to whom gonna going to call/require it.

I have prepared the snippet by keeping in mind that how we gonna re-use it as a structure in other projects too & perhaps if u see keeping server operations of API in a single module is always a good idea so far instead of using it everywhere in a bulky way. So that if an issue occurred I don’t have to go through complete project instead I can review my single file & that is the logic behind it.

Still, I would like to know from you, how I made it over complicated so that we gonna make it more feasible & ease in terms of re-use for upcoming applications.

Thanks

Assif

Well the original problem was “The problem I’m having is that I can’t access the code outside of the handleResponse function”.

Nothing you suggested (in 70-odd lines) addresses his problem.

All he needed to do was store a reference to the response so he could process the data outside of the callback.

Hi,
If u chk the server.lua listener function.
It call the callbackFunction by returning data i.e event.response.

Thus any how u will get the data outside the module in order to proceed it.

You didn’t specifically answered my question.
Its not about 72 lines.

regards,
Assif

In the code you provided response is local to the callback and will be nil when the callback completes.

You will need to scope a reference (external to the callback) to store the JSON.

You can then parse it at a later date.

Hi,

I have a prepared a callback snippet & you can use this single server.lua module for number of api methods.

Just require the server.lua in main.lua globally & use it everywhere u want the api data ith respective calback.

SERVER API  LUA MODULE

[lua]

–server.lua

local server={}

local json = require (“json”)

—=======================================Variable=========================

local headers={}

local params = {}

params.headers = headers

headers[“Content-Type”] = “application/json”

local callbackFunction

local basrUrl=“http://assif.com/

–======================Common Network  Listener===========================
 

local commonNtwrkListener =function( event )    

    if ( event.isError ) then

        print(event.isError )

        local alert = native.showAlert( “Network Error”,“Please try again.”, { “OK”})

        

    else

       --print ( "networkListener RESPONSE: " …json.prettify(event.response))

        local data = json.decode( event.response )   

        if(callbackFunction~=nil) then 

         callbackFunction(data)

        end        

    end

end

–============================API METHODS====================================

function server:fetchUserData(callback)

    callbackFunction=callback

    network.request( basrUrl…“apiMethodName”, “GET”, commonNtwrkListener, params )   

end

function server:checkUserdata(callback,dataArr)

    callbackFunction=callback

    params.body=json.encode (data)    

    network.request( basrUrl…“apiMethodName”, “POST”, commonNtwrkListener, params )   

end

-----============================================================
 

return server

[/lua]

MAIN.LUA 

[lua]

–main.lua

local server = require(“server”)


local checkUserDataCallback = function (data)

– Use Data Here…

end

 local dataArr ={name=“Assif”,pswd=“12345”}

 server:checkUserdata(checkUserDataCallback,dataArr)    


local fetchUserDataCallback = function (data)

– Use Data Here…

end

 server:fetchUserData(fetchUserDataCallback)    

[/lua]

  • Assif

Thanks for all the help!

welcome

@assif, apart from over complicating a simple network request you haven’t addressed the scoping issue of the callback being local - which was the OP problem.

Anyway, this will cure your issues (with a lot less code)

local storedData = nil local function handleResponse( event ) if not event.isError and event.response then storedData = json.decode( event.response ) end end network.request( "MY\_URL\_HERE", "GET", handleResponse) ... then later on (this does depend on the JSON returned) local value1 = storedData.value1 local value2 = storedData.value2

@spehere games

As per my snippet, the callback will be always local, being called from any of the Lua files as required.

I have kept listener, callbacks possibly local in its module.

The only thing is I have to return the reference of server.lua to whom gonna going to call/require it.

I have prepared the snippet by keeping in mind that how we gonna re-use it as a structure in other projects too & perhaps if u see keeping server operations of API in a single module is always a good idea so far instead of using it everywhere in a bulky way. So that if an issue occurred I don’t have to go through complete project instead I can review my single file & that is the logic behind it.

Still, I would like to know from you, how I made it over complicated so that we gonna make it more feasible & ease in terms of re-use for upcoming applications.

Thanks

Assif

Well the original problem was “The problem I’m having is that I can’t access the code outside of the handleResponse function”.

Nothing you suggested (in 70-odd lines) addresses his problem.

All he needed to do was store a reference to the response so he could process the data outside of the callback.

Hi,
If u chk the server.lua listener function.
It call the callbackFunction by returning data i.e event.response.

Thus any how u will get the data outside the module in order to proceed it.

You didn’t specifically answered my question.
Its not about 72 lines.

regards,
Assif