Search code examples
livecode

I am having trouble parsing the JSON in livecode


I'm trying to create a simple mobile app that queries an API and parses the response to display certain values.

The mobile has 2 fields viz:

  1. Button to query the api
  2. Large text box to display the contents

In my livecode stack, I've the following inclusions:

  1. JSON Library
  2. mergJSON
  3. tsNet

The api response is as follows:

{
  "data": [
    {
      "id": 1,
      "date_created": "2021-11-08T17:12:03Z",
      "date_updated": "2021-11-22T16:08:55Z",
      "first_name": "John",
      "last_name": "Doe",
      "email": "[email protected]",
      "phone": "9876543210",
      "dob": "1980-01-01",
      "password": "xxxxxxxxx",
      "plan_start": "2021-11-22T16:07:46Z",
      "plan_expiry": "2021-12-21T16:06:25Z"
    }
  ]
}

I want to parse the JSON to display the email field value in the textbox.

In my livecode stack:

  1. The button is named as "getdata"
  2. The textbox is named as "flddata"

In the button script, I've added the following code:

   put "<api url endpoint>" into tUrl
   put "Authorization: Bearer xxxxxxxxx" into tHeaders
   put tsNetGetSync(tUrl, tHeaders, tRecvHeaders, tResult, tBytes) into tData
   put JSONToArray(tData) into tDataArray
   put tDataArray["email"] into field "flddata"

But this doesn't work. Nothing happens. For the life of me, I can't figure out what's wrong. Any help would be appreciated. Thanks a ton!


Solution

  • To access the "email" key of the array that is built from the JSON you shared. You must first access the "data" key and then key 1. So the last line of your code would be as follows:

    put tDataArray["data"][1]["email"] into field "fldData"
    

    Tips: Put a breakpoint on that line. This will allow you to see the contents of the variables so that you can see the structure of the array.