锐英源软件
第一信赖

精通

英语

开源

擅长

开发

培训

胸怀四海 

第一信赖

当前位置:锐英源 / 开源技术 / 构造JSON字符串时怎样转义特殊字符
服务方向
人工智能数据处理
人工智能培训
kaldi数据准备
小语种语音识别
语音识别标注
语音识别系统
语音识别转文字
kaldi开发技术服务
软件开发
运动控制卡上位机
机械加工软件
软件开发培训
Java 安卓移动开发
VC++
C#软件
汇编和破解
驱动开发
联系方式
固话:0371-63888850
手机:138-0381-0136
Q Q:396806883
微信:ryysoft

构造JSON字符串时怎样转义特殊字符

{
    '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将它们处理回正确的消息?

答1

JSON uses only double quotes, not single quotes,JSON只使用双引号,而不是单引号

答2

RFC 4627 states that parsers must be able to parse conformant JSON (paragraph 4), and may support additional non-JSON extensions. However, paragraph 5 emphatically states that all producers (generators) MUST produce ONLY 100% compliant JSON. Producing JSON with frame characters that do not need escaping is an especially bad idea. Please consider replacing your apostrophes with quotes

RFC 4627声明解析器必须能够解析符合的JSON(第4段),并且可能支持其他非JSON扩展。但是,第5段着重指出,所有生产者(生产者)必须只生产100%兼容的JSON。使用不需要转义的帧字符生成JSON是一个特别糟糕的主意。请考虑用引号替换撇号

答3

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.

See this list of special character used in JSON :根据规范,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  


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

But it works, as you want it or not.

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

但是,即使它完全违反规范,作者也可以使用\'。

这很糟糕,因为:

  • 这与规格相反
  • 它不再是JSON有效字符串

但是,无论你想要与否,它都有效。

对于新读者,请始终对json字符串使用双引号。

答4

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.

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

 

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

我对这个关于基本话题这样一个备受关注的问题的高度错误信息的存在感到震惊。

JSON字符串不能用单引号引用。规范的各种版本(Douglas Crockford 的原始版本,ECMA版本和IETF版本)都声明字符串必须用双引号引用。这不是一个理论问题,也不是一个意见问题,正如目前所接受的答案所暗示的那样; 如果你试图解析单引号字符串,现实世界中的任何JSON解析器都会出错。

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

 

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

  • \"
  • \\
  • \/
  • \b
  • \f
  • \n
  • \r
  • \t
  • \u followed by 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. 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的配置文件)。相反,使用您的语言具有的任何本机映射,数组,字符串,数字,布尔值和空类型来编码要编码的数据结构,然后使用JSON编码函数将其编码为JSON。这样的函数可能内置于您正在使用的任何语言中,如JavaScript JSON.stringify,PHP json_encode或Pythonjson.dumps。如果您使用的语言没有内置此类功能,您可能会找到要使用的JSON解析和编码库。如果您只是使用语言或库函数将事物转换为JSON,那么您甚至不需要知道JSON的转义规则。这就是被误导的问题,提问者应该搞清楚事情。

答5

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 \".)每个人都在谈论如何'在一个'引用的字符串文字中逃避。这里有一个更大的问题:单引号字符串文字不是有效的JSON。JSON基于JavaScript,但它不是一回事。如果你在JavaScript代码中编写一个对象文字,那很好; 如果你真的需要JSON,你需要使用"。

使用双引号字符串,您不需要逃避'。(如果你确实想要"字符串中的文字,你可以使用\"。)

答6

' in a JSON string literal must not be escaped. Did you copy-paste it from somewhere? Maybe it's really a \u2019, not an apostrophe. My guess: someone typed it into MS Word, which turned it into a quotation mark because it thinks it knows best. Grammatically, the good old ASCII character apostrophe (', a.k.a. \x27, which we've been calling "single quote" up until now) is the one you want. But it would still be nice to fix your character encoding issue, in case there are other similar problems. So pick a character encoding, and use it for both reads and writes. Or escape using \u

'在JSON字符串中,不得对其进行转义。你从某个地方复制粘贴了吗?也许这真的是一个\u2019,而不是撇号。我的猜测:有人把它输入到MS Word中,后者将其变成了引号,因为它认为它最清楚。在语法上,好的旧ASCII字符撇号('也就是说\x27,到目前为止我们一直称之为“单引号”)是你想要的。但是,如果存在其他类似问题,修复字符编码问题仍然会很好。因此,选择一个字符编码,并将其用于读取和写入。或逃避使用\u。

答7

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:这些答案中的大多数要么不回答问题,要么在解释中不必要地长。

好的,所以JSON只使用双引号,我们得到了!

我试图使用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

Hope this helps someone.这将为你转义字符。

Mark Amery也提出了这一点,BTW很棒

希望这有助于某人。

友情链接
版权所有 Copyright(c)2004-2021 锐英源软件
公司注册号:410105000449586 豫ICP备08007559号 最佳分辨率 1024*768
地址:郑州大学北校区院(文化路97号院)内