Search code examples
c#json.net

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


In order to install an external extension into Google Chrome browser, I try to update a Chrome external extension JSON file. Using Json.NET it seems to be easy:

string fileName = "..."; // Path to a Chrome external extension JSON file

string externalExtensionsJson = File.ReadAllText(fileName);

JObject externalExtensions = JObject.Parse(externalExtensionsJson);


but I get a Newtonsoft.Json.JsonReaderException saying:

"Error parsing comment. Expected: *, got /. Path '', line 1, position 1."


when calling JObject.Parse because this file contains:

// This JSON file will contain a list of extensions that will be included
// in the installer.

{
}

And comments are not part of JSON (as seen in How do I add comments to Json.NET output?).

I know I can remove comments with a regular expression (Regular expression to remove JavaScript double slash (//) style comments), but I need to rewrite JSON into the file after modification and keeping comment can be a good thing.

Is there a way to read JSON content with comments without removing them and be able to rewrite them?


Solution

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

    Update: Json.NET 6.0 supports single line comments