How to escape special characters in building a JSON string?

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

Here is my string

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


        
11条回答
  •  鱼传尺愫
    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 \".)

提交回复
热议问题