如何在构建JSON字符串时避开特殊字符?

时间:2022-07-02 22:24:46

Here is my string

这是我的字符串

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

Here the message contains single quotation mark, which is same as the quotation used in JSON. What I do is fill up a string from user inputs such as message. So, I need to escape those kind of special scenarios which breaks the code. But other than string replace, is there any way to make them escape but still allow HTML to process them back to the correct message?

这里的消息包含单引号,与JSON中使用的引用相同。我所做的就是从用户输入(如消息)中填充一个字符串。因此,我需要逃离那些破坏代码的特殊场景。但是除了字符串替换,还有什么方法可以让它们脱逃,但仍然允许HTML将它们处理回正确的消息吗?

9 个解决方案

#1


196  

A JSON string must be double-quoted, according to the specs, so you don't need to escape '.
If you have to use special character in your JSON string, you can escape it using \ character.

根据规范,JSON字符串必须是双引号,所以您不需要转义。如果您必须在JSON字符串中使用特殊字符,您可以使用\字符来避免它。

See this list of special character used in 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


However, even if it is totally contrary to the spec, the author could use \'.

然而,即使它与规范完全相反,作者也可以使用\'。

This is bad because :

这很糟糕,因为:

  • It IS contrary to the specs
  • 这与规格不符。
  • It is no-longer JSON valid string
  • 它不再是JSON有效字符串。

But it works, as you want it or not.

但不管你想不想,它都能起作用。

For new readers, always use a double quotes for your json strings.

对于新读者,总是使用双引号作为json字符串。

#2


257  

I'm appalled by the presence of highly-upvoted misinformation on such a highly-viewed question about a basic topic.

对于这样一个关于一个基本话题的高度评价的错误信息,我感到震惊。

JSON strings cannot be quoted with single quotes. The various versions of the spec (the original by Douglas Crockford, the ECMA version, and the IETF version) all state that strings must be quoted with double quotes. This is not a theoretical issue, nor a matter of opinion as the accepted answer currently suggests; any JSON parser in the real world will error out if you try to have it parse a single-quoted string.

JSON字符串不能单引号引用。规范的各种版本(由Douglas Crockford、ECMA版本和IETF版本的版本)所有的字符串都必须引用双引号。这不是一个理论问题,也不是目前公认的答案所表明的意见问题;如果您试图让它解析一个单引号字符串,那么在真实世界中任何JSON解析器都会出错。

Crockford's and ECMA's version even display the definition of a string using a pretty picture, which should make the point unambiguously clear:

Crockford和ECMA的版本甚至使用漂亮的图片来显示字符串的定义,这一点应该清楚地表明:

如何在构建JSON字符串时避开特殊字符?

The pretty picture also lists all of the legitimate escape sequences within a JSON string:

这个漂亮的图片还列出了JSON字符串中所有合法的转义序列:

  • \"
  • \”
  • \\
  • \ \
  • \/
  • \ /
  • \b
  • \ b
  • \f
  • \ f
  • \n
  • \ n
  • \r
  • r \
  • \t
  • \ t
  • \u followed by four-hex-digits
  • \ u four-hex-digits紧随其后

Note that, contrary to the nonsense in some other answers here, \' is never a valid escape sequence in a JSON string. It doesn't need to be, because JSON strings are always double-quoted.

请注意,与这里其他一些答案中的废话相反,“\”从来都不是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.

最后,当编程生成JSON时,您通常不需要考虑转义字符(当然,您当然会在手动编辑时,比如基于JSON的配置文件)。相反,您需要使用任何本地映射、数组、字符串、数字、布尔值和空类型来编码数据结构,然后用JSON编码函数将其编码为JSON。这样的函数可能构建在您使用的任何语言中,比如JavaScript的JSON。stringify, PHP的json_encode,或Python的json.dump。如果您使用的语言没有内置这样的功能,您可能会找到一个JSON解析和编码库来使用。如果您只是使用语言或库函数来将事物转换成JSON,那么您甚至不需要知道JSON的转义规则。这就是这个被误导的问题应该做的。

#3


20  

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 ".

每个人都在谈论如何“用”引用的字符串字面意思逃离。这里有一个更大的问题:单引号的字符串文本不是有效的JSON。JSON是基于JavaScript的,但这不是一回事。如果你在JavaScript代码中写一个对象文字,很好;如果您确实需要JSON,那么您需要使用“。

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

使用双引号字符串,您就不需要脱离“。”(如果你确实想要一个文字“在字符串中,你会用\”)。

#4


4  

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!

JSON只使用双引号,我们明白了!

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:

我尝试使用JQuery AJAX将JSON数据发送到服务器,然后返回相同的信息。我找到的问题的最佳解决方案是:

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

这也是Mark Amery提出的,很棒的答案。

Hope this helps someone.

希望这可以帮助别人。

#5


1  

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)..

可能是我太迟了,但这将解析/退出单引号(不要陷入解析vs . escape的战斗中)..

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

#6


1  

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

直接问题的答案是:要安全,用\u+4-digit-hex值替换需要的字符。

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

例子:如果你想要摆脱撇号的替换,用\u0027 D' amico变成D\u0027Amico。

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

很好的参考:http://es5.github.io/x7.html # x7.8.4

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

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

#7


0  

This is an issue if you include your data in an html file the following way (using ejs template engine):

这是一个问题,如果您将您的数据包含在一个html文件中(使用ejs模板引擎):

<script>
  var MY_APP = { data: JSON.parse('<%-JSON.stringify(data)%>'};
</script>

if data contains a string with single quotes this will error, unless you convert ' to \' which is only possible by the string "\\\'"

如果数据包含有单引号的字符串,则会出现错误,除非您将“to”转换为“\”,只有字符串“\\”才可能。

<script>var BRANCHE = { data: JSON.parse('<%-
  JSON.stringify(data).replace("'","\\\'")%>')};
</script>

Not pretty, but works.

不漂亮,但作品。

#8


-1  

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.

我想我们都同意单引号的jsons不是真正的jsons。尽管如此,我们仍然需要解决“在一个双引号的json字符串中,在没有库的情况下为我们这样做”的问题。

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 ").

相反,首先用\(双反斜杠)替换每个\。只有这样,用“\”(反斜杠后面跟着)来替换它们。

#9


-7  

regarding AlexB's post:

关于AlexB的文章:

 \'  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

转义单引号只在单引号内有效,转义的双引号只在双引号的json字符串中有效。

example:

例子:

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

#1


196  

A JSON string must be double-quoted, according to the specs, so you don't need to escape '.
If you have to use special character in your JSON string, you can escape it using \ character.

根据规范,JSON字符串必须是双引号,所以您不需要转义。如果您必须在JSON字符串中使用特殊字符,您可以使用\字符来避免它。

See this list of special character used in 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


However, even if it is totally contrary to the spec, the author could use \'.

然而,即使它与规范完全相反,作者也可以使用\'。

This is bad because :

这很糟糕,因为:

  • It IS contrary to the specs
  • 这与规格不符。
  • It is no-longer JSON valid string
  • 它不再是JSON有效字符串。

But it works, as you want it or not.

但不管你想不想,它都能起作用。

For new readers, always use a double quotes for your json strings.

对于新读者,总是使用双引号作为json字符串。

#2


257  

I'm appalled by the presence of highly-upvoted misinformation on such a highly-viewed question about a basic topic.

对于这样一个关于一个基本话题的高度评价的错误信息,我感到震惊。

JSON strings cannot be quoted with single quotes. The various versions of the spec (the original by Douglas Crockford, the ECMA version, and the IETF version) all state that strings must be quoted with double quotes. This is not a theoretical issue, nor a matter of opinion as the accepted answer currently suggests; any JSON parser in the real world will error out if you try to have it parse a single-quoted string.

JSON字符串不能单引号引用。规范的各种版本(由Douglas Crockford、ECMA版本和IETF版本的版本)所有的字符串都必须引用双引号。这不是一个理论问题,也不是目前公认的答案所表明的意见问题;如果您试图让它解析一个单引号字符串,那么在真实世界中任何JSON解析器都会出错。

Crockford's and ECMA's version even display the definition of a string using a pretty picture, which should make the point unambiguously clear:

Crockford和ECMA的版本甚至使用漂亮的图片来显示字符串的定义,这一点应该清楚地表明:

如何在构建JSON字符串时避开特殊字符?

The pretty picture also lists all of the legitimate escape sequences within a JSON string:

这个漂亮的图片还列出了JSON字符串中所有合法的转义序列:

  • \"
  • \”
  • \\
  • \ \
  • \/
  • \ /
  • \b
  • \ b
  • \f
  • \ f
  • \n
  • \ n
  • \r
  • r \
  • \t
  • \ t
  • \u followed by four-hex-digits
  • \ u four-hex-digits紧随其后

Note that, contrary to the nonsense in some other answers here, \' is never a valid escape sequence in a JSON string. It doesn't need to be, because JSON strings are always double-quoted.

请注意,与这里其他一些答案中的废话相反,“\”从来都不是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.

最后,当编程生成JSON时,您通常不需要考虑转义字符(当然,您当然会在手动编辑时,比如基于JSON的配置文件)。相反,您需要使用任何本地映射、数组、字符串、数字、布尔值和空类型来编码数据结构,然后用JSON编码函数将其编码为JSON。这样的函数可能构建在您使用的任何语言中,比如JavaScript的JSON。stringify, PHP的json_encode,或Python的json.dump。如果您使用的语言没有内置这样的功能,您可能会找到一个JSON解析和编码库来使用。如果您只是使用语言或库函数来将事物转换成JSON,那么您甚至不需要知道JSON的转义规则。这就是这个被误导的问题应该做的。

#3


20  

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 ".

每个人都在谈论如何“用”引用的字符串字面意思逃离。这里有一个更大的问题:单引号的字符串文本不是有效的JSON。JSON是基于JavaScript的,但这不是一回事。如果你在JavaScript代码中写一个对象文字,很好;如果您确实需要JSON,那么您需要使用“。

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

使用双引号字符串,您就不需要脱离“。”(如果你确实想要一个文字“在字符串中,你会用\”)。

#4


4  

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!

JSON只使用双引号,我们明白了!

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:

我尝试使用JQuery AJAX将JSON数据发送到服务器,然后返回相同的信息。我找到的问题的最佳解决方案是:

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

这也是Mark Amery提出的,很棒的答案。

Hope this helps someone.

希望这可以帮助别人。

#5


1  

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)..

可能是我太迟了,但这将解析/退出单引号(不要陷入解析vs . escape的战斗中)..

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

#6


1  

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

直接问题的答案是:要安全,用\u+4-digit-hex值替换需要的字符。

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

例子:如果你想要摆脱撇号的替换,用\u0027 D' amico变成D\u0027Amico。

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

很好的参考:http://es5.github.io/x7.html # x7.8.4

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

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

#7


0  

This is an issue if you include your data in an html file the following way (using ejs template engine):

这是一个问题,如果您将您的数据包含在一个html文件中(使用ejs模板引擎):

<script>
  var MY_APP = { data: JSON.parse('<%-JSON.stringify(data)%>'};
</script>

if data contains a string with single quotes this will error, unless you convert ' to \' which is only possible by the string "\\\'"

如果数据包含有单引号的字符串,则会出现错误,除非您将“to”转换为“\”,只有字符串“\\”才可能。

<script>var BRANCHE = { data: JSON.parse('<%-
  JSON.stringify(data).replace("'","\\\'")%>')};
</script>

Not pretty, but works.

不漂亮,但作品。

#8


-1  

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.

我想我们都同意单引号的jsons不是真正的jsons。尽管如此,我们仍然需要解决“在一个双引号的json字符串中,在没有库的情况下为我们这样做”的问题。

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 ").

相反,首先用\(双反斜杠)替换每个\。只有这样,用“\”(反斜杠后面跟着)来替换它们。

#9


-7  

regarding AlexB's post:

关于AlexB的文章:

 \'  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

转义单引号只在单引号内有效,转义的双引号只在双引号的json字符串中有效。

example:

例子:

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