How to encode post content as JSON?

To output JSON always the function json_encode( $string ). The function is not available on all hosts. Don’t worry, WordPress offers a fallback in wp-includes/compat.php. That’s a wrapper for class Services_JSON::encodeUnsafe() (see wp-includes/class-json.php).
If you take a look at the source you’ll see: It’s not a trivial job to encode a string. 🙂

There is a small difference: The native PHP json_encode() accepts a second parameter $options since PHP 5.3.0. The WordPress fallback doesn’t.

New lines are encoded as '\n' in JSON; you cannot get the same output as in the HTML tab in TinyMCE.

And there is, of course, also a fallback for json_decode() in case you need it.

Leave a Comment