How to escape special characters in building a JSON string?

后端 未结 11 798
北恋
北恋 2020-11-22 04:18

Here is my string

{
    \'user\': {
        \'name\': \'abc\',
        \'fx\': {
            \'message\': {
                \'color\': \'red\'
            }         


        
相关标签:
11条回答
  • 2020-11-22 04:40

    Using template literals...

    var json = `{"1440167924916":{"id":1440167924916,"type":"text","content":"It's a test!"}}`;
    
    0 讨论(0)
  • 2020-11-22 04:49

    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.

    0 讨论(0)
  • 2020-11-22 04:51

    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.

    0 讨论(0)
  • 2020-11-22 04:53

    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.

    0 讨论(0)
  • 2020-11-22 04:55

    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
    
    0 讨论(0)
提交回复
热议问题