Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 861
MuiBienCarlota Avatar asked Apr 25 '12 13:04

MuiBienCarlota


People also ask

How do you comment in a JSON file?

To do this, you need to add an element to your JSON file, such as "_comment," which will contain your comment.

Can JSON have comments?

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.

Does Newtonsoft JSON support comments?

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.


2 Answers

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

Update: Json.NET 6.0 supports single line comments

like image 121
James Newton-King Avatar answered Oct 02 '22 14:10

James Newton-King


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; } 
like image 32
shane-o Avatar answered Oct 02 '22 13:10

shane-o