rokubrightscript

JSON Parsing using Brightscript for ROKU app


I need to parse JSON received from API calls. Can anyone please suggest me any example link as I am not getting JSON parsing example at Roku blog.


Solution

  • Based on Roku docs,

    Let's say you have an API response like this:

    {
          "photos" : [
               {  
                     "title" : "View from the hotel",
                     "url" : "http://example.com/images/00012.jpg" 
               },
               { 
                     "title" : "Relaxing at the beach",
                     "url" : "http://example.com/images/00222.jpg" 
               },
               { 
                     "title" : "Flat tire",
                     "url" : "http://example.com/images/00314.jpg" 
               }
          ]
    }
    

    Then, to interact with the response is as follows:

    searchRequest = CreateObject("roUrlTransfer")
    searchRequest.SetURL("http://api.example.com/services/rest/getPhotos")
    response = ParseJson(searchRequest.GetToString())
    For Each photo In response.photos
        GetImage(photo.title, photo.url)
    End For
    

    You can see more details here

    Notice that you need to set some certificates to make requests here.

    It's important to understand the whole functionality, however, there are some libs you can use to make request less painful. Usually, you end up creating your own wrapper.

    I'm not the owner of this repo, I've have seen this NewHttp function on several projects.

    In case you want to use that wrapper, you can do it as follows:

    m.http = NewHttp(url,invalid,"GET")
    m.http.AddHeader("X-Roku-Reserved-Dev-Id", "")
    response = m.http.GetToStringWithTimeout(10)  
    
    if m.http.GetResponseCode() <> 200 then
        print "Error while trying to get the response, ResponseCode:", m.http.GetResponseCode()
    else 'the Response Code was 200(OK)'
       response = ParseJson(rsp)
    end if
    

    Hope this helps!