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).
To output JSON always the function
json_encode( $string )
. The function is not available on all hosts. Don’t worry, WordPress offers a fallback inwp-includes/compat.php
. That’s a wrapper forclass Services_JSON::encodeUnsafe()
(seewp-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/