How to escape special characters in building a JSO

2018-12-31 09:02发布

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
9条回答
零度萤火
2楼-- · 2018-12-31 09:36

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

查看更多
谁念西风独自凉
3楼-- · 2018-12-31 09:44

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.

查看更多
无与为乐者.
4楼-- · 2018-12-31 09:47

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

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

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

Not pretty, but works.

查看更多
千与千寻千般痛.
5楼-- · 2018-12-31 09:56

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

查看更多
人间绝色
6楼-- · 2018-12-31 09:57

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("\"'\"")
查看更多
梦该遗忘
7楼-- · 2018-12-31 09:57

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

查看更多
登录 后发表回答