What is the minimum valid JSON?

The short, but entirely unhelpful, answer to this question is that… it depends; it depends on both what the language you are sending from, and receiving to, deems as the minimum valid JSON.

For example, if you are sending JSON between PHP and a browser (in either direction), the minimum valid JSON is a JSON literal. Between a browser and Ruby however, it is a JSON object (or array).

The reason for this lack of consensus is best explained by the “creator” of JSON himself; Douglas Crockford:

JSON is just a grammar, and the grammar includes numbers and strings. Uses of JSON must necessarily be more restrictive. RFC-4627 is one possible use, and was never intended to be the standard for JSON itself.

So yeah. You don’t just send or receive “JSON”. Technically, you receive a JSON formatted text which adheres to a particular format; commonly described in a standard. RFC-4627 is one of those. ECMA-404 is another. RFC-4627 defines a JSON array/ object as the minimum valid JSON, whilst ECMA-404 permits JSON literals (JSONValue‘s in the spec.) as well.

This is why you need to look at the documentation for the stringifer and parser you are using; to check what standard they adhere to.

To make things more confusing however, many JSON implementations do not perfectly adhere to a particular specification, and will add their own exceptions to their implementation. This is why JSON literals are accepted as valid JSON between PHP and browsers; as even though both technically adhere to RFC-4627, both also specifically add the exception that they also accept JSON literals as well as JSON object/arrays as the minimum JSON (relevant part of the ECMAScript 5 spec., relevant part of the PHP docs.).

With Ruby on Rails however, no exceptions exist; it adheres to RFC-4627 plain and simple. So whilst browsers can create and parse JSON texts which contain only literals, Ruby on Rails cannot parse or create them itself.

This post summarises the content of two answers on Stack Overflow; my own answer to ‘What is the minimum valid JSON’, and other answer by Jeremy Banks to ‘After the publication of ECMA-404, is ‘2’ or ‘”hello”‘ considered a valid JSON text?’.

Leave a Reply

Your email address will not be published. Required fields are marked *