我已经生成了一些 JSON,并尝试将其拉入 JavaScript 中的对象中。我不断收到错误。这是我所拥有的

var data = '{"count" : 1, "stack" : "sometext\n\n"}';
var dataObj = eval('('+data+')');

这给了我一个错误

unterminated string literal

JSON.parse(data), ,我看到类似的错误消息:”Unexpected token ↵“在 Chrome 中,以及”unterminated string literal“在 Firefox 和 IE 中。

当我取出 \nsometext 在这两种情况下错误都会消失。我似乎不明白为什么 \n 使 evalJSON.parse 失败。

有帮助吗?

解决方案

我想这就是你想要的:

var data = '{"count" : 1, "stack" : "sometext\\n\\n"}';

(您需要转义字符串中的“\”(将其变成双“\”),否则它将成为 JSON 源中的换行符,而不是 JSON 数据。)

其他提示

你需要有一个函数来代替 \n\\n 以防万一 data 不是字符串文字。

function jsonEscape(str)  {
    return str.replace(/\n/g, "\\\\n").replace(/\r/g, "\\\\r").replace(/\t/g, "\\\\t");
}

var data = '{"count" : 1, "stack" : "sometext\n\n"}';
var dataObj = JSON.parse(jsonEscape(data));

结果 dataObj

Object {count: 1, stack: "sometext\n\n"}

根据规格: http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf

A string is a sequence of Unicode code points wrapped with quotation marks
(U+0022). All characters may be placed within the quotation marks except for the
characters that must be escaped: quotation mark (U+0022), reverse solidus
(U+005C), and the control characters U+0000 to U+001F. There are two-character
escape sequence representations of some characters.

所以你无法通过 0x0A 或者 0x0C 直接编码。这是被禁止的!规范建议对一些定义良好的代码使用转义序列 U+0000U+001F:

\f  represents the form feed character (U+000C). 
\n  represents the line feed character (U+000A).

正如大多数编程语言使用的那样 \ 为了引用,你应该转义转义语法(双重转义 - 一次用于语言/平台,一次用于 Json 本身):

jsonStr = "{ \"name\": \"Multi\\nline.\" }";

例如,您可以在写入 json 字段的值时在服务器中转义字符串,并在客户端浏览器中检索值时取消转义它。

所有主流浏览器的 javascript 实现都有 unescape 命令。

例子:在服务器中:

response.write "{""field1"":""" & escape(RS_Temp("textField")) & """}"

在浏览器中:

document.getElementById("text1").value = unescape(jsonObject.field1)

您可能想查看这个 C# 函数来转义字符串:

http://www.aspcode.net/C-encode-a-string-for-JSON-JavaScript.aspx

public static string Enquote(string s)  
{ 
    if (s == null || s.Length == 0)  
    { 
        return "\"\""; 
    } 
    char         c; 
    int          i; 
    int          len = s.Length; 
    StringBuilder sb = new StringBuilder(len + 4); 
    string       t; 

    sb.Append('"'); 
    for (i = 0; i < len; i += 1)  
    { 
        c = s[i]; 
        if ((c == '\\') || (c == '"') || (c == '>')) 
        { 
            sb.Append('\\'); 
            sb.Append(c); 
        } 
        else if (c == '\b') 
            sb.Append("\\b"); 
        else if (c == '\t') 
            sb.Append("\\t"); 
        else if (c == '\n') 
            sb.Append("\\n"); 
        else if (c == '\f') 
            sb.Append("\\f"); 
        else if (c == '\r') 
            sb.Append("\\r"); 
        else 
        { 
            if (c < ' ')  
            { 
                //t = "000" + Integer.toHexString(c); 
                string t = new string(c,1); 
                t = "000" + int.Parse(tmp,System.Globalization.NumberStyles.HexNumber); 
                sb.Append("\\u" + t.Substring(t.Length - 4)); 
            }  
            else  
            { 
                sb.Append(c); 
            } 
        } 
    } 
    sb.Append('"'); 
    return sb.ToString(); 
} 

您好,我使用此函数去除数据中的换行符或其他字符来解析 JSON 数据:

function normalize_str($str) {

    $invalid = array('Š'=>'S', 'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z',
    'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A',
    'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E', 'Ê'=>'E', 'Ë'=>'E',
    'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
    'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y',
    'Þ'=>'B', 'ß'=>'Ss', 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a',
    'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e', 'ê'=>'e',  'ë'=>'e', 'ì'=>'i', 'í'=>'i',
    'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o',
    'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y',  'ý'=>'y', 'þ'=>'b',
    'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r', "`" => "'", "´" => "'", '"' => ',', '`' => "'",
    '´' => "'", '"' => '\"', '"' => "\"", '´' => "'", "&acirc;€™" => "'", "{" => "",
    "~" => "", "–" => "-", "'" => "'","     " => " ");

    $str = str_replace(array_keys($invalid), array_values($invalid), $str);

    $remove = array("\n", "\r\n", "\r");
    $str = str_replace($remove, "\\n", trim($str));

      //$str = htmlentities($str,ENT_QUOTES);

    return htmlspecialchars($str);
}


echo normalize_str($lst['address']);

我在 PHP4 中创建一个类来模拟 json_encode (在 PHP5 中可用)时遇到了这个问题。这是我想出的:

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.'"';
    }
}

我遵守了提到的规则 这里。我只使用了我需要的东西,但我认为您可以根据您正在使用的语言的需要进行调整。我的情况的问题不是像我最初想象的那样与换行符有关,而是与 / 没有被转义有关。我希望这可以防止其他人因我弄清楚我做错了什么而感到头疼。

删除单引号(提示: eval==evil)

var dataObj = {"count" : 1, "stack" : "sometext\n\n"};

console.log(dataObj);

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top