How to parse JSON

Hi,

I’m having troubles parsing some JSON stuff. I’m talking to an website API over Oauth and getting some JSON as return

Here’s some of my main.lua code:

local request\_response = oAuth.makeRequest("http://api.mysite.com/users/list.json", params, consumer\_key, access\_token, consumer\_secret, access\_token\_secret, "GET" )   
  
local myCode\_encoded = json.encode(request\_response)  
local myCode\_decoded = json.decode(myCode\_encoded)  
  
print (myCode\_decoded)   
  

This outputs the following JSON:

[{"id":"1","email":"some@email.com","username":"someuser","firstname":"James","lastname":"Wilson","country":"UK","city":"London","address":"Oxfordstreet 55","latlng":"50.12345,3.123456","work":"Developer","sex":"male","biography":"Apple fan, ...","gardenSize":"950.00"},{"id":"2","email":"some@othermail.com","username":"azerty","firstname":"Rick","lastname":"Astley","country":"UK","city":"London","address":"Oxfordstreet","latlng":"","work":"","sex":"male","biography":""}]  

How do i select the separate nodes for each record ?

This doesn’t work:

 print(myCode\_encoded.id[1])  

It gives me an error:

Runtime error: main.lua:37: attempt to index field ‘id’ (a nil value)
Who can help me on my way ?

Thx

Lieven [import]uid: 13439 topic_id: 13134 reply_id: 313134[/import]

Try something like this:

print(myCode_decoded[“id”])
print(myCode_decoded[“email”])

Jay

[import]uid: 9440 topic_id: 13134 reply_id: 48221[/import]

Hi Jay,

print(myCode\_decoded["id"])  

Nope … that just gives me a “nil” !
Any other idea’s ?

Lieven [import]uid: 13439 topic_id: 13134 reply_id: 48274[/import]

This tutorial, just posted, might be useful for you:

http://blog.anscamobile.com/2011/08/tutorial-exploring-json-usage-in-corona/ [import]uid: 52430 topic_id: 13134 reply_id: 48653[/import]

Hi Jonathan,

I noticed that my JSON output starts and ends with “[]”.
Does this mean it’s not decoded successfully ?

Any idea’s ?

I tried some things from your blogpost, but without success :frowning:
Lieven [import]uid: 13439 topic_id: 13134 reply_id: 48659[/import]

ok, I think i understand why I’m getting a nil… my JSON that i’m getting from the server is interpreted as a string, not as a JSON object.

How can i convert that JSON string to real JSON (in a table) ?
Lieven [import]uid: 13439 topic_id: 13134 reply_id: 48673[/import]

print(myCode_encoded[1].id) perhaps?
Looks like a array containing objects being returned from the server. [import]uid: 14451 topic_id: 13134 reply_id: 48785[/import]

I found a solution for my problem.

I was first encoding the json that was returned and then decoding it.
If I only decode it (without encoding) then it works fine.

Thanks all for the help.

Lieven [import]uid: 13439 topic_id: 13134 reply_id: 48789[/import]