Problem when retrieving text in JSON format containing line breaks with jQuery

人盡茶涼 提交于 2019-11-27 11:53:47

If you would like to keep the line breaks, you might try:

function parse($text) {
    // Damn pesky carriage returns...
    $text = str_replace("\r\n", "\n", $text);
    $text = str_replace("\r", "\n", $text);

    // JSON requires new line characters be escaped
    $text = str_replace("\n", "\\n", $text);
    return $text;
}

Line breaks aren't the issue so much as they need to be properly escaped in JSON. If it's available to you, you can use json_encode which automatically escapes newlines. Failing that, you can use something like Pim Jager's method above, though a proper JSON encoder would be best.

I encountered that problem while making a class in PHP4 to emulate json_encode (available in PHP5). Here's what i came up with :

class jsonResponse {
    var $response;

    function jsonResponse() {
        $this->response = array('isOK'=>'KO','msg'=>'Undefined');
    }

    function set($isOK, $msg) {
        $this->response['isOK'] = ($isOK) ? 'OK' : 'KO';
        $this->response['msg'] = htmlentities($msg);
    }

    function setData($data=null) {
        if(!is_null($data))
            $this->response['data'] = $data;
        elseif(isset($this->response['data']))
            unset($this->response['data']);
    }

    function send() {
        header('Content-type: application/json');
        echo '{"isOK":"'.$this->response['isOK'].'","msg":'.$this->parseString($this->response['msg']);
        if(isset($this->response['data']))
            echo ',"data":'.$this->parseData($this->response['data']);
        echo '}';
    }

    function parseData($data) {
        if(is_array($data)) {
            $parsed = array();
            foreach ($data as $key=>$value)
                array_push($parsed, $this->parseString($key).':'.$this->parseData($value));
            return '{'.implode(',', $parsed).'}';
        } else
            return $this->parseString($data);
    }

    function parseString($string) {
            $string = str_replace("\\", "\\\\", $string);
            $string = str_replace('/', "\\/", $string);
            $string = str_replace('"', "\\".'"', $string);
            $string = str_replace("\b", "\\b", $string);
            $string = str_replace("\t", "\\t", $string);
            $string = str_replace("\n", "\\n", $string);
            $string = str_replace("\f", "\\f", $string);
            $string = str_replace("\r", "\\r", $string);
            $string = str_replace("\u", "\\u", $string);
            return '"'.$string.'"';
    }
}

I followed the rules mentionned here. I only used what i needed but i figure that you can adapt it to your needs in the language your are using. The problem in my case wasn't about newlines as i originally thought but about the / not being escaped. I hope this prevent someone else from the little headache i had figuring out what i did wrong.

do you get linebreaks like <br /> or newlines like \n? But try to replace them with PHP.

<?php
$string = 'asdfasf<br />asdfasf';
echo str_replace('<br />', '', $strin); // Replace <br /> with '' (nothing)
?>

or check out urlencode

Like Terw but with replacing \n

<?php
 $json = str_replace('\n', '', $json);
?>

Should remove all line breaks, jquery shouldn't fail over
tags, but line breaks should not be in JSON.

r4wi

Have you tried this

update tablename set field_name_with_\r\n_in_it = replace(field_name_with_\r\n_in_it,"\r\n","<br />")

It worked for me on mysql 5.0.45

Easy, just try:

<?php
...
function parseline($string){
  $string = str_replace(chr(10), "//n", $string);
  $string = str_replace(chr(13), "//n", $string);
  return $string;
}

echo parseline($string_with_line_breaks);//returns json readable text

I have tested it and it works perfect. No need to add complicated functions.

If the other responses didn't work, it's possible to strip all whitespace characters except the space.

PHP $text = trim(preg_replace( "/[\\x00-\\x19]+/" , '' , $text));

From: https://github.com/joomla/joomla-cms/issues/14502

You can also use <pre> tag that will keep all line breaks and white spaces. I am posting this answer because i also encounter that problem and for solutions i reached to this question and after that I randomly decided to use <pre> tag instead of <div> and that solved by problem although at many places there were unwanted back slashes \

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!