[Answered] Handling HTTP Request data

Hello, after creating a HTTP Get request my api returns the following data:
[{"playerID":55,"money":436,"bounty":1}]

I used the decodeJSON function to turn this into a table.
After doing so, I tried to print out the result by doing :
print(data.playerID)

(data being the decoded table)
This seems to return ‘nil’ however rather than returning the playerID (55).
I have tried this numerous times and it keeps on returning nil.

I can’t seem to work out why it does this? Does anyone have experience with handling the result?

Can you show the code snippet where you decode it?

1 Like

It looks to me like you return an array containing an object.
Try doing print(data[1].playerId), the [1] represents that you want the first item within the array.
Pretty much this is what data looks like after you used JSONDecode:

{
  {
    playerId: 55
    money: 436,
    bounty: 1
  }
}
1 Like

@Polyheximal

Can you show the code snippet where you decode it?

 function decodeJson(json) 
    local jsonTab = {} pcall(function ()     
       jsonTab = HttpService:JSONDecode(json)     
    end) return jsonTab     
 end

@SimplyData

It looks to me like you return an array containing an object.
Try doing print(data[1].playerId) , the [1] represents that you want the first item within the array.

It prints it out after I choose to print data[1]

The code on the backend is handled to return a JSON array so this would make sense. I do this incase of any errors. Obviously since in this case there we none it just returned the results.

No worries, you can either update your API to return something like this

{
    "success": true,
    "data": {
        "playerId": "yourId",
        "money": 500,
        "bounty": 1
    }
}

and check if success is true, or you just change your data variable to local data = decodeJson(response)[1] (or whatever it looks like for you)

I will probably do that as it makes error handling more consistent. Thanks for your help guys…