JSON Tips - Don't use GetAsText() to generate JSON data

Do not use GetAsText() to generate JSON

I saw the question about JSON data and I was reminded that I have seen a lot of people use GetAsText() on different datatypes to push data into JSON.

Yes, JSON is text, and your data is not. But if your data is not already text then you don't want to use the GetAsText() function.

The built-in JSON tools allow you to specify exactly what sort of object it is. Half of the options describe structures, the other half describe what type of thing it is. The choices for data are: String, Number, Boolean.

If your data is in a container then you want Base64Encode() or Base64EncodeRFC() to generate text from your binary data.

If your data isn't in a container, and it isn't already text, then you want to use GetAsNumber().

GetAsNumber() will transform dates, times, and timestamps into a number. Numbers transmit perfectly well in JSON. Both of the following forms will transmit the date in number format. The same is true for time fields, and timestamp fields.

JSONSetElement ( $json ; "date" ; GetAsNumber ( table::dateField ) ; JSONNumber ) 
JSONSetElement ( $json ; "date" ; GetAsNumber ( table::dateField ) ; 2 )

At the other end, all you have to do is to use the appropriate GetAs... function. Those functions will transform the number back into the date, time, or timestamp.

GetAsDate( JSONGetElement ( $json ; "date" ) ) 
GetAsTime( JSONGetElement ( $json ; "time" ) )
GetAsTimeStamp( JSONGetElement ( $json ; "timestamp" ) )

The nicest thing about using a number is that you don't have to jump through hoops to recreate the original data. No-one wants to parse string representations of timestamps. Simply use a number, and no one will ever have to, the original object is recreated perfectly without any fuss.

4 Likes

I would say it depends if integration is a requirement.

For example, there is increasing requirement to store date, time and timestamp values in JSON as ISO 8601 string values of YYYY-MM-DD, hh:mm:ss and YYYY-MM-DDThh:mm:ss / YYYY-MM-DDThh:mm:ss±hh:mm, respectively.

When someone else is setting the rules, meet those rules. However, if you're using JSON as an easy way to pass information from FileMaker to FileMaker then storing dates, times, and timestamps as numbers for transmission via JSON is dead simple.

2 Likes