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?
To do this, you need to add an element to your JSON file, such as "_comment," which will contain your comment.
No. JSON is data-only. If you include a comment, then it must be data too. You could have a designated data element called "_comment" (or something) that should be ignored by apps that use the JSON data.
No, JSON is a data-only format. Comments in the form //, #, or /* */, which are used in popular programming languages, are not allowed in JSON. You can add comments to JSON as custom JSON elements that will hold your comments, but these elements will still be data.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With