JSON에서 줄바꿈을 어떻게 처리하나요?
-
09-06-2019 - |
문제
일부 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에서.
내가 꺼낼 때 \n
~ 후에 sometext
두 경우 모두 오류가 사라집니다.나는 그 이유를 알 수 없는 것 같다. \n
만든다 eval
그리고 JSON.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
직접 코드.그것은 금지되어 있습니다!Spec에서는 잘 정의된 코드에 대해 이스케이프 시퀀스를 사용할 것을 제안합니다. U+0000
에게 U+001F
:
\f represents the form feed character (U+000C).
\n represents the line feed character (U+000A).
대부분의 프로그래밍 언어가 사용하는 것처럼 \
인용하려면 이스케이프 구문을 이스케이프해야 합니다(이중 이스케이프 - 언어/플랫폼에 한 번, Json 자체에 한 번).
jsonStr = "{ \"name\": \"Multi\\nline.\" }";
예를 들어, json 필드의 값을 쓸 때 서버에서 문자열을 이스케이프하고 클라이언트 브라우저에서 값을 검색할 때 이스케이프를 취소할 수 있습니다.
모든 주요 브라우저의 자바스크립트 구현에는 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', "`" => "'", "´" => "'", '"' => ',', '`' => "'",
'´' => "'", '"' => '\"', '"' => "\"", '´' => "'", "’" => "'", "{" => "",
"~" => "", "–" => "-", "'" => "'"," " => " ");
$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']);
json_encode(PHP5에서 사용 가능)를 에뮬레이트하기 위해 PHP4에서 클래스를 만드는 동안 해당 문제가 발생했습니다.내가 생각해낸 내용은 다음과 같습니다.
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);