I`m trying to construct a json object but are having difficulties with the_content since it returns newlines, which causes the script to fail. The error messages received is: Uncaught SyntaxError: Unexpected token ILLEGAL

Example of the json:

[ {image : 'http://localhost/wp-content/uploads/2012/04/example.png', title: 'Example string

with newlines
that outputs illegally!'}]

Ideally I'd want it to output the HTML content (as seen when pressing the HTML tab in the editor).


2 Answers 2


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.


You also have a wp function : wp_json_encode() that can do the job https://developer.wordpress.org/reference/functions/wp_json_encode/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.