Keith Clark Keith Clark - 2 months ago 15
HTML Question

C# Convert string to JSON errors

Part of a public class I have builds a data structure for dataTables plugin.

The code to build the data structure is:

var response = "{ \"data\": [";
response = response + "[";
response = response + "\"Clark, Keith\",";
response = response + "\"Corporate\",";
response = response + "\"XXX-XXX-XXXX\",";
response = response + "\"XXX-XXX-XXXX\",";
response = response + "\"XXXX@XXXX.com\"";
response = response + "],";
response = response + "[";
response = response + "\"Clark, Keith\",";
response = response + "\"Corporate\",";
response = response + "\"YYY-YYY-YYYY\",";
response = response + "\"YYY-YYY-YYYY\",";
response = response + "\"YYYY@XXXX.com\"";
response = response + "]";
response = response + "] }";

return response;


This runs fine and creates the table as expected. Where I am running into issues is when I try to add HTML markup to a field. I want to use a font awesome icon next to the name to indicate status like this:

<i class="fa fa-arrow-up" style="color: #00ff00;" aria-hidden="true">


I have tried modifying my code to read:

response = response + "\"<i class=\"\"fa fa-arrow-up\"\" style=\"\"color: #00ff00;\"\" aria-hidden=\"\"true\"\">Clark, Keith\",";


But now I am receiving an error that the JSON is not properly formatted. Am I missing something or can HTML markup not be used inside a JSON structure?

Answer

The problem is that you're generating an invalid json string literal.

"<i class=""fa fa-arrow-up"" style=""color: #00ff00;"" aria-hidden=""true"">Clark, Keith",

Quotes are escaped using literal backslashes, not doubling them.

You would have had to do this instead:

"\"<i class=\\\"fa fa-arrow-up\\\" style=\\\"color: #00ff00;\\\" aria-hidden=\\\"true\\\">Clark, Keith\","

This demonstrates why exactly you shouldn't be generating strings like this. There are tools out there that can do this for you and safely, use them. Json.net will make easy work out of this.

var markup = "<i class=\"fa fa-arrow-up\" style=\"color: #00ff00;\" aria-hidden=\"true\">";
var response = new JObject
{
    ["data"] = new JArray
    {
        new JArray
        {
            markup + "Clark, Keith",
            "Corporate",
            "XXX-XXX-XXXX",
            "XXX-XXX-XXXX",
            "XXXX@XXXX.com",
        },
        new JArray
        {
            markup + "Clark, Keith",
            "Corporate",
            "YYY-YYY-YYYY",
            "YYY-YYY-YYYY",
            "YYYY@XXXX.com",
        },
    }
};
return response.ToString();

With that said, you shouldn't be adding markup to your data. Data is data and nothing more. If you want to affect how it is displayed, that markup should be added to your view.

Comments