ToString with unquoted object names

Jun 25, 2009 at 12:10 AM

I'm working with a jQuery plugin that expects object literals as pair names rather than quoted strings as pair names:

 

{ property1: "value1", property2: "value2" }

not:

 

{ "property1": "value1", "property2": "value2" }

 

The easiest way I found to handle this is an extension on JObject.ToString():

 

public static string ToString(this JObject self, bool quote)
{
    using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
    {
        JsonTextWriter jw = 
            new JsonTextWriter(sw)
                {
                    QuoteName = quote, 
                    Formatting = Formatting.Indented
                };
        self.WriteTo(jw);
        return sw.ToString();
    }
}

Is there a better way to handle this?
Many thanks! 

 

 

 

 

Coordinator
Jun 25, 2009 at 9:38 AM

No, that is the pretty good.

I haven't tested or touched anything with name quoting turned off in years. Glad it works with LINQ to JSON :)

Jun 25, 2009 at 4:17 PM

All tests passing thus far :)

Thanks for a fantastic library!