<<css mode="next" class="sidebar"></css>> (((
- '''<a href="/docs/fJSON">Class Documentation</a>''' - <a href="/api/fJSON">API Reference</a> - <a href="https://github.com/flourishlib/flourish-classes/blob/master/fJSON.php" target="_blank">Source Code</a>
<<toc></toc>> )))
The fJSON class is primarily a compatibility class to allow for encoding and decoding JSON strings on server running PHP 5.0 and 5.1—PHP 5.2 comes bundled with `json_encode()` and `json_decode()`. In addition, the class provides a simple method to send the proper headers with a JSON response.
The methods ::encode() and ::decode() allow for encoding and decoding JSON respectively. For servers that do have the `json` PHP extension, the `json` extension functions will be used. A native PHP implementation will automatically be used for server that do not have the `json` extension installed.
`encode()` takes a single parameter, the PHP value to encode. Associative arrays will be encoded as JSON objects, with the rest of PHP data types being converted into the equivalent JSON data type. Technically all valid JSON needs to be either an array or an object, however the PHP `json` extension does not follow this restriction.
The following PHP
would output the following JSON:
`decode()` takes a JSON string and will convert it into the equivalent PHP data types. An optional second parameter `$assoc` when set to `TRUE` will cause JSON objects to be converted to associative arrays instead of an instance of the PHP class `stdClass`.
The following PHP
would output the following text:
If you are returning JSON in a response, calling the ::sendHeader() mehod will ensure that the `Content-Type` header is set to the correct value of `application/json; charset=utf-8`.
Usually when writing a script that creates JSON, the header will need to be sent and a PHP value will need to be encoded and output. The static method ::output() does all of this.