Programing

JSON 문자열을 만들 때 특수 문자를 이스케이프 처리하는 방법은 무엇입니까?

crosscheck 2020. 5. 17. 15:44
반응형

JSON 문자열을 만들 때 특수 문자를 이스케이프 처리하는 방법은 무엇입니까?


여기 내 줄이있다

{
    'user': {
        'name': 'abc',
        'fx': {
            'message': {
                'color': 'red'
            },
            'user': {
                'color': 'blue'
            }
        }
    },
    'timestamp': '2013-10-04T08: 10: 41+0100',
    'message': 'I'mABC..',
    'nanotime': '19993363098581330'
}    

여기 메시지에는 작은 따옴표가 포함되어 있는데 이는 JSON에 사용 된 인용 부호와 동일합니다. 내가하는 일은 메시지와 같은 사용자 입력에서 문자열을 채우는 것입니다. 따라서 코드를 손상시키는 특수 시나리오를 피해야합니다. 그러나 문자열 바꾸기 이외의 방법으로 HTML을 올바른 메시지로 다시 처리 할 수 ​​있습니까?


사양 에 따라 JSON 문자열을 큰 따옴표로 묶어야 하므로 이스케이프 할 필요가 없습니다 '.
JSON 문자열에 특수 문자를 사용해야하는 경우 문자를 사용하여 특수 문자를 이스케이프 처리 할 수 ​​있습니다 \.

JSON에서 사용되는 다음 특수 문자 목록을 참조하십시오.

\b  Backspace (ascii code 08)
\f  Form feed (ascii code 0C)
\n  New line
\r  Carriage return
\t  Tab
\"  Double quote
\\  Backslash character


그러나 사양과 완전히 반대되는 경우에도 작성자는을 사용할 수 있습니다 \'.

이것은 나쁘기 때문에 :

  • 사양에 위배됩니다
  • 더 이상 JSON 유효하지 않은 문자열입니다.

그러나 원하는대로 작동합니다.

새로운 독자의 경우 항상 json 문자열에 큰 따옴표를 사용하십시오.


나는 기본 주제에 대한 그러한 높은 시각의 질문에 대해 고도로 반박 된 잘못된 정보가 존재한다는 사실에 놀랐습니다.

작은 따옴표로 JSON 문자열 을 인용 할 수 없습니다 . 스펙의 다양한 버전 ( 더글러스 크록 포드 의 원본 , ECMA 버전IETF 버전 )에는 모두 문자열을 큰 따옴표로 묶어야한다고 명시되어 있습니다. 이것은 받아 들여진 대답이 현재 제시하고있는 이론적 인 문제 나 의견의 문제가 아니다. 작은 따옴표로 묶인 문자열을 구문 분석하려고하면 실제 세계의 모든 JSON 파서가 오류가 발생합니다.

Crockford와 ECMA의 버전은 예쁜 그림을 사용하여 문자열의 정의를 표시하기 때문에 요점을 명확하게 알 수 있습니다.

JSON 사양에서 문자열의 정의를 보여주는 이미지

예쁜 그림에는 JSON 문자열 내의 모든 합법적 인 이스케이프 시퀀스도 나열되어 있습니다.

  • \"
  • \\
  • \/
  • \b
  • \f
  • \n
  • \r
  • \t
  • \u 뒤에 4 자리 숫자가옵니다

여기의 다른 답변에서 넌센스와 달리 \'JSON 문자열에서 유효한 이스케이프 시퀀스는 결코 아닙니다. JSON 문자열은 항상 큰 따옴표로 묶기 때문에 필요하지 않습니다.

Finally, you shouldn't normally have to think about escaping characters yourself when programatically generating JSON (though of course you will when manually editing, say, a JSON-based config file). Instead, form the data structure you want to encode using whatever native map, array, string, number, boolean, and null types your language has, and then encode it to JSON with a JSON-encoding function. Such a function is probably built into whatever language you're using, like JavaScript's JSON.stringify, PHP's json_encode, or Python's json.dumps. If you're using a language that doesn't have such functionality built in, you can probably find a JSON parsing and encoding library to use. If you simply use language or library functions to convert things to and from JSON, you'll never even need to know JSON's escaping rules. This is what the misguided question asker here ought to have done.


Everyone is talking about how to escape ' in a '-quoted string literal. There's a much bigger issue here: single-quoted string literals aren't valid JSON. JSON is based on JavaScript, but it's not the same thing. If you're writing an object literal inside JavaScript code, fine; if you actually need JSON, you need to use ".

With double-quoted strings, you won't need to escape the '. (And if you did want a literal " in the string, you'd use \".)


Most of these answers either does not answer the question or is unnecessarily long in the explanation.

OK so JSON only uses double quotation marks, we get that!

I was trying to use JQuery AJAX to post JSON data to server and then later return that same information. The best solution to the posted question I found was to use:

var d = {
    name: 'whatever',
    address: 'whatever',
    DOB: '01/01/2001'
}
$.ajax({
    type: "POST",
    url: 'some/url',
    dataType: 'json',
    data: JSON.stringify(d),
    ...
}

This will escape the characters for you.

This was also suggested by Mark Amery, Great answer BTW

Hope this helps someone.


May be i am too late to the party but this will parse/escape single quote (don't want to get into a battle on parse vs escape)..

JSON.parse("\"'\"")

The answer the direct question:
To be safe, replace the required character with \u+4-digit-hex-value

Example: If you want to escape the apostrophe ' replace with \u0027
D'Amico becomes D\u0027Amico

NICE REFERENCE: http://es5.github.io/x7.html#x7.8.4

https://mathiasbynens.be/notes/javascript-escapes


Use encodeURIComponent() to encode the string.

Eg. var product_list = encodeURIComponent(JSON.stringify(product_list));

You don't need to decode it since the web server automatically do the same.


To allow single quotes within doubule quoted string for the purpose of json, you double the single quote. {"X": "What's the question"} ==> {"X": "What''s the question"}

https://codereview.stackexchange.com/questions/69266/json-conversion-to-single-quotes

The \' sequence is invalid.


I think we all agree single quoted jsons aren't real jsons. Be that as it may, we still need to address the question of escaping " within a double quoted json string, in the absence of libraries to do so for us.

Replacing each " with a \" is NOT ENOUGH: User may enter the input: \ and parsing, again, fails (think why).

Instead, first replace each \ with \ (double backslash). Only then, replace each " with \" (backslash followed by ").


regarding AlexB's post:

 \'  Apostrophe or single quote
 \"  Double quote

escaping single quotes is only valid in single quoted json strings
escaping double quotes is only valid in double quoted json strings

example:

'Bart\'s car'       -> valid
'Bart says \"Hi\"'  -> invalid

참고 URL : https://stackoverflow.com/questions/19176024/how-to-escape-special-characters-in-building-a-json-string

반응형