How to escape special characters in building a JSON string?

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

Here is my string

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


        
11条回答
  •  一生所求
    2020-11-22 04:32

    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 :

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

提交回复
热议问题