How to encode post content as JSON?

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:

Read More
[ {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).

Related posts

Leave a Reply

2 comments

  1. 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.