Tech Tip: Correct practice when sending JSON to a web client with no data
PRODUCT: 4D | VERSION: 14.0 | PLATFORM: Mac & Win
Published On: July 14, 2014
When 4D sends text to a web client as "text/json" the receiving client evaluates the response as JSON and creates a JavaScript object. The JSON data is parsed in a "strict" manner; any malformed JSON is rejected and a parse error is thrown.
When there is no data to return from a web query it is incorrect to send an empty string when using "text/json" as the MIME type, WEB SEND TEXT(''). An empty response will most likely generate an error in the web client.
When no data is to be sent, the proper response for 4D is to send an empty JSON object, {}. See the code snippet below.
If ($Request_T#"") // Create 4D Language object // C_OBJECT($Fields_O) // Fill the object // ... // Convert the 4D Language object to a JSON string // $JSON_T:=JSON Stringify($Fields_O) Else // Send an empty JSON object {}, DO NOT SEND AN EMPTY STRING // $JSON_T:="{}" // NOT $JSON_T:="" End if WEB SEND TEXT($JSON_T;"text/json") |
See Also: