How do I handle newlines in JSON?

后端 未结 10 1328
后悔当初
后悔当初 2020-11-22 05:28

I\'ve generated some JSON and I\'m trying to pull it into an object in JavaScript. I keep getting errors. Here\'s what I have:

var data = \'{\"count\" : 1, \         


        
10条回答
  •  太阳男子
    2020-11-22 06:14

    I encountered that problem while making a class in PHP 4 to emulate json_encode (available in PHP 5). 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 mentioned 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.

提交回复
热议问题