How to escape special characters in building a JSON string?

后端 未结 11 797
北恋
北恋 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.

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

    I'm appalled by the presence of highly-upvoted misinformation on such a highly-viewed question about a basic topic.

    JSON strings cannot be quoted with single quotes. The various versions of the spec (the original by Douglas Crockford, the ECMA version, and the IETF version) all state that strings must be quoted with double quotes. This is not a theoretical issue, nor a matter of opinion as the accepted answer currently suggests; any JSON parser in the real world will error out if you try to have it parse a single-quoted string.

    Crockford's and ECMA's version even display the definition of a string using a pretty picture, which should make the point unambiguously clear:

    Image showing the definition of a string from the JSON spec

    The pretty picture also lists all of the legitimate escape sequences within a JSON string:

    • \"
    • \\
    • \/
    • \b
    • \f
    • \n
    • \r
    • \t
    • \u followed by four-hex-digits

    Note that, contrary to the nonsense in some other answers here, \' is never a valid escape sequence in a JSON string. It doesn't need to be, because JSON strings are always double-quoted.

    Finally, you shouldn't normally have to think about escaping characters yourself when programatically generating JSON (though of course you will when manually editing, say, a JSON-based config file). Instead, form the data structure you want to encode using whatever native map, array, string, number, boolean, and null types your language has, and then encode it to JSON with a JSON-encoding function. Such a function is probably built into whatever language you're using, like JavaScript's JSON.stringify, PHP's json_encode, or Python's json.dumps. If you're using a language that doesn't have such functionality built in, you can probably find a JSON parsing and encoding library to use. If you simply use language or library functions to convert things to and from JSON, you'll never even need to know JSON's escaping rules. This is what the misguided question asker here ought to have done.

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

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

    0 讨论(0)
  • 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("\"'\"")
    
    0 讨论(0)
  • 2020-11-22 04:39

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

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

    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

    0 讨论(0)
提交回复
热议问题