Search code examples
javascriptjsonjson.nethtml-encode

Html in json - how to make it valid (with javascript)?


I'm using json.net to automatically deserialize my json objects into .net objects. As long as the json is valid, it works a treat.

But I'm having trouble with html in the json...the special characters and quotes are making the json invalid.

How do I encode or escape the html reliably so it's valid json? I need a way to do it with just javascript because it's the client side sending to the server side.

Edit Just to give an example of my use case, I have a WYSIWYG in my app and I need the input from that included as part of a json object to be posted to my server.


Solution

  • Just to give an example of my use case, I have a WYSIWYG in my app and I need the input from that included as part of a json object to be posted to my server.

    Assuming you have the user input in a string variable:

    var userInput = 'Any crap with HTML you can imagine';
    

    You can simply JSON encode this in order to transport it as a valid JSON string:

    var json = JSON.stringify({ value = userInput });
    

    Now the resulting object will look like this:

    {
        "value": "Any crap with HTML you can imagine"
    }
    

    and on your server simply map this to a POCO with a plain Value string property. The JSON.stringify method will ensure to properly serialize any input to a valid JSON string.

    This being said, I don't quite understand your need of wrapping the user input in a JSOn string and then deserializing it back on the server with JSON.NET. I would rather send the raw input as-is. This way you would get exactly the same value on the server without the overhead of JSON serialization.