Javascript – Multi-line elements in JSON


I would like to use JSON for sending multiple variables like status, error-message and content to a Javascript function via Ajax.

The problem I'm having is that I fetch the content from a database and almost all data that is sent back to the browser is multi-line. And because of that it seems like my JSON is not validated.

An example of outout might be:

    "status" : "ok",
    "message" : "All is well",
    "contents" : "Lorem Ipsum

    Dolor sit amet"

Is there any special way of handling multi-line that I've missed or is it plain impossible (seems unlikely)?


Best Solution

Since they are control characters, you can't have literal new lines in JSON strings.

See the spec:

New lines are represented as \n, but you shouldn't need to worry about that, because your JSON encoding library should take care of that for you. Since it isn't you either have a library with a bug (in which case I suggest fixing it, reporting it, or looking for an alternative) or you aren't using a library (in which case – get one).