How to escape special characters in building a JSON string?

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

Here is my string

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


        
11条回答
  •  北海茫月
    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.

提交回复
热议问题