[javascript] JavaScript를 사용하여 줄 바꿈 문자가 포함 된 JSON 문자열을 이스케이프 처리하는 방법은 무엇입니까?

값에 줄 바꾸기 문자가있는 JSON 문자열을 형성해야합니다. 이스케이프 처리 한 다음 AJAX 호출을 사용하여 게시해야합니다. JavaScript로 문자열을 이스케이프 처리하는 방법을 제안 할 수 있습니까? jQuery를 사용하지 않습니다.



답변

JSON을 가져 가십시오 .stringify(). 그런 다음 .replace()방법을 사용하고 모든 발생을 \n로 바꿉니다 \\n.

편집하다:

내가 아는 한 문자열에서 모든 특수 문자를 이스케이프 처리하는 잘 알려진 JS 라이브러리는 없습니다. 그러나 .replace()메소드를 연결하고 다음과 같이 모든 특수 문자를 바꿀 수 있습니다 .

var myJSONString = JSON.stringify(myJSON);
var myEscapedJSONString = myJSONString.replace(/\\n/g, "\\n")
                                      .replace(/\\'/g, "\\'")
                                      .replace(/\\"/g, '\\"')
                                      .replace(/\\&/g, "\\&")
                                      .replace(/\\r/g, "\\r")
                                      .replace(/\\t/g, "\\t")
                                      .replace(/\\b/g, "\\b")
                                      .replace(/\\f/g, "\\f");
// myEscapedJSONString is now ready to be POST'ed to the server. 

그러나 그것은 매우 불쾌하지 않습니까? 함수의 아름다움을 입력하면 코드를 여러 조각으로 나누고 스크립트의 주요 흐름을 깨끗하게 유지하고 8 개의 체인 .replace()호출을 피할 수 있습니다. 이 기능을이라는 함수에 넣겠습니다 escapeSpecialChars(). 계속 prototype chain해서 String객체 의 객체에 escapeSpecialChars()연결하여 String 객체를 직접 호출 할 수 있습니다 .

이렇게 :

String.prototype.escapeSpecialChars = function() {
    return this.replace(/\\n/g, "\\n")
               .replace(/\\'/g, "\\'")
               .replace(/\\"/g, '\\"')
               .replace(/\\&/g, "\\&")
               .replace(/\\r/g, "\\r")
               .replace(/\\t/g, "\\t")
               .replace(/\\b/g, "\\b")
               .replace(/\\f/g, "\\f");
};

해당 함수를 정의하면 코드의 본문은 다음과 같이 간단합니다.

var myJSONString = JSON.stringify(myJSON);
var myEscapedJSONString = myJSONString.escapeSpecialChars();
// myEscapedJSONString is now ready to be POST'ed to the server


답변

사용자에 따라 백 슬래시 교체를 먼저 재정렬하고 견적 교체를 수정하는 것을 제외하고는 667073이 제안했습니다.

escape = function (str) {
  return str
    .replace(/[\\]/g, '\\\\')
    .replace(/[\"]/g, '\\\"')
    .replace(/[\/]/g, '\\/')
    .replace(/[\b]/g, '\\b')
    .replace(/[\f]/g, '\\f')
    .replace(/[\n]/g, '\\n')
    .replace(/[\r]/g, '\\r')
    .replace(/[\t]/g, '\\t');
};


답변

당신처럼, 나는 여러 주석을 조사하고 그 안에 html 객체를 포함하는 JSON의 특수 이스케이프 문자를 대체하기 위해 게시했습니다.

내 객체는 JSON 객체의 특수 문자를 제거하고 json 객체 내부의 HTML을 렌더링하는 것입니다.

여기 내가 한 일이 있으며 사용이 매우 간단하기를 바랍니다.

먼저 JSON.stringify 내 json 객체와 JSON.parse를 수행했습니다.

예를 들어 :

JSON.parse(JSON.stringify(jsonObject));

그리고 그것은 내 문제를 해결하고 Pure Javascript를 사용하여 완료되었습니다.


답변

Alex가 제공 한 답변이 다소 틀렸다고 말하기가 두렵습니다.

  • Alex가 이스케이프하려고하는 일부 문자는 (& 및 ‘와 같은) 이스케이프 할 필요가 없습니다.
  • \ b는 백 스페이스 문자가 아니라 단어 경계가 일치합니다.
  • 이스케이프해야하는 문자는 처리되지 않습니다.

이 기능

escape = function (str) {
    // TODO: escape %x75 4HEXDIG ?? chars
    return str
      .replace(/[\"]/g, '\\"')
      .replace(/[\\]/g, '\\\\')
      .replace(/[\/]/g, '\\/')
      .replace(/[\b]/g, '\\b')
      .replace(/[\f]/g, '\\f')
      .replace(/[\n]/g, '\\n')
      .replace(/[\r]/g, '\\r')
      .replace(/[\t]/g, '\\t')
    ; };

더 나은 근사치 인 것 같습니다.


답변

작은 따옴표에 대한 작은 업데이트

function escape (key, val) {
    if (typeof(val)!="string") return val;
    return val
        .replace(/[\\]/g, '\\\\')
        .replace(/[\/]/g, '\\/')
        .replace(/[\b]/g, '\\b')
        .replace(/[\f]/g, '\\f')
        .replace(/[\n]/g, '\\n')
        .replace(/[\r]/g, '\\r')
        .replace(/[\t]/g, '\\t')
        .replace(/[\"]/g, '\\"')
        .replace(/\\'/g, "\\'");
}

var myJSONString = JSON.stringify(myJSON,escape);


답변

이것은 오래된 게시물입니다. angular.fromJson 및 JSON.stringify를 사용하는 사람들에게는 여전히 도움이 될 수 있습니다. escape ()는 더 이상 사용되지 않습니다. 대신 이것을 사용하십시오

var uri_enc = encodeURIComponent(uri); //before you post the contents
var uri_dec = decodeURIComponent(uri_enc); //before you display/use the contents.

심판 http://www.w3schools.com/jsref/jsref_decodeuricomponent.asp


답변

JSON.stringify에는 두 번째 매개 변수도 있습니다. 따라서 더 우아한 해결책은 다음과 같습니다.

function escape (key, val) {
    if (typeof(val)!="string") return val;
    return val
      .replace(/[\"]/g, '\\"')
      .replace(/[\\]/g, '\\\\')
      .replace(/[\/]/g, '\\/')
      .replace(/[\b]/g, '\\b')
      .replace(/[\f]/g, '\\f')
      .replace(/[\n]/g, '\\n')
      .replace(/[\r]/g, '\\r')
      .replace(/[\t]/g, '\\t')
    ;
}

var myJSONString = JSON.stringify(myJSON,escape);