How can I read JSON content with a comment with Json.NET?

Json.NET only supports reading multi-line JavaScript comments, i.e. /* commment */

Update: Json.NET 6.0 supports single line comments


If you are stuck with JavaScriptSerializer (from the System.Web.Script.Serialization namespace), I have found that this works good enough...

private static string StripComments(string input)
{
    // JavaScriptSerializer doesn't accept commented-out JSON,
    // so we'll strip them out ourselves;
    // NOTE: for safety and simplicity, we only support comments on their own lines,
    // not sharing lines with real JSON

    input = Regex.Replace(input, @"^\s*//.*$", "", RegexOptions.Multiline);  // removes comments like this
    input = Regex.Replace(input, @"^\s*/\*(\s|\S)*?\*/\s*$", "", RegexOptions.Multiline); /* comments like this */

    return input;
}

Tags:

C#

Json.Net