removeing comments from json

Feb 7, 2012 at 2:07 PM

Hi there,

heres is what im trying todo:

i want parse some json from a file an then serialize it again but without! the comments contained in the original file.

I tried it like this:

var o = JsonConvert.DeserializeObject(sb2.ToString());                

var s = JsonConvert.SerializeObject(o, Formatting.None);

But that approach seems to keep the comments.

Any hints?

Thanks, J.

Feb 21, 2012 at 1:10 AM
Edited Feb 21, 2012 at 1:11 AM

I'm using regex to remove single line comments after storing the raw json record into a string variable called fileDataWithSingleLineComments and before parsing with json:

 

// remove single line comments before parsing
fileDataWithoutSingleLineComments = Regex.Replace(fileDataWithSingleLineComments, @"(^[//]{2}[^\n]*)|([\n]{1,}[\/]{2}[^\n]*)", " ");

 JObject.Parse(fileDataWithoutSingleLineComments);

//parse into Linq
jsonRecordWithoutSingleLineComments = Newtonsoft.Json.Linq.

Feb 21, 2012 at 8:23 AM

Thanks for your reply, i acutually ended up doing this:

 

 var o = JsonConvert.DeserializeObject(sb2.ToString()) as JObject;
                    var e = o.GetEnumerator();
                    while (e.MoveNext())
                    {
                        if(e.Current.Value is JArray)
                        {
                            var ja = e.Current.Value as JArray;
                            for(int j=0;j< ja.Count;j++)
                            {
                                var c = ja[j];
                                if(c.Type == JTokenType.Comment)
                                {
                                    c.Remove();
                                }
                            }
                        }
                    }
var s = JsonConvert.SerializeObject(o, Formatting.None);

Cheers,

J.