如何在构建JSON字符串时转义特殊字符? [英] How to escape special characters in building a JSON string?

查看:669
本文介绍了如何在构建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将其处理回正确的消息?

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字符串双引号.您不需要转义'.
如果必须在JSON字符串中使用特殊字符,则可以使用\字符对其进行转义.

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中使用的特殊字符列表:

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

这是不好,因为:

  • 违反规范
  • 它不再是JSON有效字符串

但是不管您想要与否,它都可以工作.

But it works, as you want it or not.

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

这篇关于如何在构建JSON字符串时转义特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆