How to encode the single quote/apostrophe in JSON.NET

前端 未结 4 1499
花落未央
花落未央 2021-02-08 18:55

How to encode the \' to \\u0027 with JSON.NET?

So that the json string would look something like this:

{\"Id\":8,\"CompanyName         


        
4条回答
  •  孤街浪徒
    2021-02-08 19:23

    I assumed I had the same requirement, but @nick_w's comment made me realise I didn't need to escape the single quotes at all.

    If you are generating json as a string in server side code, then outputting it into the client side javascript, so it can be converted to javascript objects, then escaping is not required.

    (Code shown using asp style syntax)

    Using extra steps requiring escaping single quotes...

    var myData = JSON.parse('<%=myServerGeneratedStringWithSingleQuotesEscaped %>');
    

    Using the JSON as it is...

    var myData = <%=myServerGeneratedString %>;
    

    Javascript will interpret an unquoted string such as

    [{"name":"Bill"}, {"name":"Ted"}]

    as javascript objects.

    As it's so easy to get mixed up when dealing with server side and client side strings, this reminder may be useful to someone. It may or may not apply to the OP - I'm sure there are many cases where single quotes genuinely need escaping.

提交回复
热议问题