Your Digital Media Has Never Looked So Good

 
User avatar
RokuKC
Posts: 315
Joined: Wed Sep 10, 2014 10:44 am
Location: Roku HQ

Re: Built-in ToJSON function

Thu Oct 30, 2014 5:12 pm

Thanks for the documentation feedback.

A note has been added to the FormatJSON documentation to indicate that it is not supported on the 3.1 firmware.
 
dcrandall
Posts: 74
Joined: Wed Jul 30, 2014 11:04 am

Re: Built-in ToJSON function

Wed Nov 05, 2014 10:11 am

kurtn718 wrote:
Hi. Is there a built-in ToJSON function, similar to ParseJSON?

I couldn't find one in the docs, but I was able to write the following function taking an roAssociativeArray as the input - which works for what I need.

If there is a built-in function, I'll probably replace the code below with that function. If one doesn't exist, then this is my first contribution to the forum. :) If there is a way to write the code better, please offer suggestions.

Thanks,

Kurt
-------
Function ToJSON(jsonData as Object) as String
jsonRequest = "{"
for each key in jsonData
if jsonRequest <> "{" then
jsonRequest = jsonRequest + ","
endif

jsonRequest = jsonRequest + chr(34) + key + chr(34) + " : " + chr(34) + jsonData[key] + chr(34)
end for
jsonRequest = jsonRequest + "}"

return jsonRequest
End Function


Just as a note for posterity, you might have to use the roAssociativeArray function "AddReplace" to preserve case-sensitivity.
 
EnTerr
** Valued Community Member **
Posts: 3834
Joined: Sun Jan 02, 2011 2:41 am

Re: Built-in ToJSON function

Wed Nov 05, 2014 11:17 am

dcrandall wrote:
Just as a note for posterity, you might have to use the roAssociativeArray function "AddReplace" to preserve case-sensitivity.

You mean before externalizing to JSON, while creating the data structure - if one does not want all keys to turn lowercase?

Using AddReplace() is not enough though. `dict.AddReplace(key, value)` is equivalent to `dict[key] = value` - it will preserve the key case once but if another key2 is used later that differs in letter-case only, that will clobber the first one:
BrightScript Debugger> h = { }
BrightScript Debugger> h["KeY"] = "value"     
BrightScript Debugger> ? h
KeY: value

BrightScript Debugger> h["kEy"] = "eulaV"
BrightScript Debugger> ? h
kEy: eulaV

The solution includes two steps:
  1. Call SetModeCaseSensitive() on the hashes destined for case-sensitive websites
  2. Don't use dot-operator to assign them, use []= or AddReplace() instead

Who is online

Users browsing this forum: No registered users and 17 guests