Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

share|improve this question
add comment

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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