Why is it a valid JSON?

So, I am wondering, why does Json.NET consider this string to be valid JSON?

{message:'Welcome to real world'}

It's not valid according to RFC 7159.

Sample code that doesn't throw an exception (as I'd expect it to):

public void Lol()
    var deserialized = Newtonsoft.Json.JsonConvert
        .DeserializeObject<IHaveBadNewsForYou>("{message:'Welcome to real world'}");

class IHaveBadNewsForYou
    public string Message { get; set; }
Jon Skeet

Json.NET is just being lenient. It's not valid JSON, for two reasons:

  • The member name isn't quoted
  • The string uses single quotes instead of double quotes

I don't think there's any way of getting Json.NET to be absolutely strict about what JSON it will allow. (I know there are some aspects of number handling that definitely can't be made strict, for example - I had to write my own parser for that reason.)

Json.NET will produce valid JSON by default, I believe - although you can alter settings to produce invalid JSON in some ways.

I suspect many other JSON handling libraries are lenient, but possibly in varying ways. For example, comments aren't valid in JSON, but the use of // as "line comments" is pretty common, so I suspect many parsers handle that. Likewise a trailing comma after the last property of an object is logically-harmless, but strictly-invalid. The aspects of which quote characters to accept and whether names can be unquoted or not may well vary significantly.

The question of how lenient a parser should be is a matter of opinion to some extent. Personally I prefer strict parsing in general, as otherwise you end up with pseudo-standards and documents that can be parsed by some libraries but not others, with everyone claiming that their way is best :( In this case I'd argue that libraries are trying to deal with deficiencies in the JSON specification itself - at least in terms of how JSON is very often used (for hand-written and human-read configuration files, where things like comments and trailing commas are incredibly useful).


See more on this question at Stackoverflow