What Is the Minimum Valid JSON

What is the minimum valid JSON?

At the time of writing, JSON was solely described in RFC4627. It describes (at the start of "2") a JSON text as being a serialized object or array.

This means that only {} and [] are valid, complete JSON strings in parsers and stringifiers which adhere to that standard.

However, the introduction of ECMA-404 changes that, and the updated advice can be read here. I've also written a blog post on the issue.


To confuse the matter further however, the JSON object (e.g. JSON.parse() and JSON.stringify()) available in web browsers is standardised in ES5, and that clearly defines the acceptable JSON texts like so:

The JSON interchange format used in this specification is exactly that described by RFC 4627 with two exceptions:

  • The top level JSONText production of the ECMAScript JSON grammar may consist of any JSONValue rather than being restricted to being a JSONObject or a JSONArray as specified by RFC 4627.

  • snipped

This would mean that all JSON values (including strings, nulls and numbers) are accepted by the JSON object, even though the JSON object technically adheres to RFC 4627.

Note that you could therefore stringify a number in a conformant browser via JSON.stringify(5), which would be rejected by another parser that adheres to RFC4627, but which doesn't have the specific exception listed above. Ruby, for example, would seem to be one such example which only accepts objects and arrays as the root. PHP, on the other hand, specifically adds the exception that "it will also encode and decode scalar types and NULL".

Is [] valid JSON?

Part 1: Is "[]" valid JSON?

There are several documents and standards on JSON, and hundreds of parsers; and some of them suppose that JSON can only be object {} or an array [], but some allow single values like strings, numbers to be used as JSON.

Read this article, it widely describes this problem.

What is the minimum valid JSON?

This dispute on JSON validity is another question. In your case, it doesn't matter, because...

Part 2: why your code isn't working.

Even if we allow non-objects \ non-arrays to be valid JSON, then your JSON represents a single string equal to "[]". It could be anything else, not brackets, it is not an array notation, but just two symbols "[" and "]".

However, you try to parse this JSON as an array of objects, which will anyway result into error.

In other words, even if it is a valid JSON, then it is a valid JSON string, not JSON array.

var str1 = JSON.parse("\"[]\""),    str2 = JSON.parse("\"could be anything else, not brackets\""),    arr = JSON.parse("[]");    console.log(typeof str1);console.log(typeof str2);console.log(typeof arr);
var str1_s = JSON.stringify([]);console.log("Valid JSON of an empty array: " + str1_s);var arr_s = JSON.stringify("[]");console.log("Partly valid JSON of a string '[]': " + arr_s);

Is this simple string considered valid JSON?

Yes, in most contexts. It is valid JSON syntax representing a JSON value.

The confusion around this comes from Douglas Crockford's RFC 4627, which originally defined the application/json internet media type in 2006. It said that:

A JSON text is a serialized object or array.

However, as Crockford explained in a post in 2013 (unfortunately deleted with rest of Google+, but archived here):

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.

The example string is a valid JSON value, but it would have been incorrect to use it as the full "JSON text" body of an application/json HTTP response. However, that's no longer true: RFC-4627 was obsoleted in 2014 with the publication of RFC 7159, which lets you use any JSON value:

A JSON text is a serialized value. Note that certain previous specifications of JSON constrained a JSON text to be an object or an array.

A "standard for JSON itself" was also published in 2013, as ECMA-404, and JSON was also defined in edition 5.1 of the ECMAScript (JavaScript) specification ECMA-262. These specifications and most parsers allow any JSON value as a complete JSON text, even if it's just a simple string.

Minimal JSON data structure containing a value

Per ECMA-404, The JSON Data Interchange Standard (pdf), which is linked from the JSON.org page you linked:

A JSON text is a sequence of tokens formed from Unicode code points that conforms to the JSON value grammar.

And:

A JSON value can be an object, array, number, string, true, false, or null.

As such, the value 123 is valid JSON, representing an integer.

Why is one number valid json?

Parsing a number

You can better handle the parsing of numbers using parseInt(). It will return a number on success and NaN (Not a Number) otherwise.

var a = parseInt('23');
isNan(a); // false

var b = parseInt('ab');
isNan(b); // true

Why it returns 1 in jQuery

If you have a look at the source of the jQuery method it will become clear very quickly.

  1. It will check if there is native support for JSON.parse.
  2. If not, it will create an anonymous function (with string body) that simply returns the data contained in the JSON string and calls it.

So if in your case step 2. is executed it will simply return 1 even though it's not real JSON.

UPDATE:
I was curious how the native JSON.parse would handle it and it does the same thing (returning 1). So regardless of the implementation you always get the same result.

Library on display: http://code.jquery.com/jquery-1.8.3.js

parseJSON: function( data ) {
if ( !data || typeof data !== "string") {
return null;
}

// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );

// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}

// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {

return ( new Function( "return " + data ) )(); // Just returns JSON data.

}
jQuery.error( "Invalid JSON: " + data );
},

Are booleans valid JSON

The validator you link to validates the JSON string existing of a mere true as invalid according to RFC 4627, which dictates that the root of a JSON string is to be an array or object:

A JSON text is a serialized object or array.

 JSON-text = object / array

An unwrapped value such as true or "foo" or 42 is not JSON according to that RFC.

The other RFCs it can validate against, RFC 7159 and RFC 8259, deem the above examples valid as it does not constrain a JSON text to objects or arrays, but also allows values:

A JSON value MUST be an object, array, number, or string, or one of
the following three literal names:

 false null true

And because the former (RFC 4627) is obsoleted by the latter two (RFC 7159 respectively 8259), true is a valid JSON string.

Are JSON values valid JSON?

As of March 2014: Yes. From the specification:

A JSON text is a serialized value. Note that certain previous
specifications of JSON constrained a JSON text to be an object or an
array. Implementations that generate only objects or arrays where a
JSON text is called for will be interoperable in the sense that all
implementations will accept these as conforming JSON texts.

However, at the time this question was originally asked, the answer was: No. The original specification said:

A JSON text is a serialized object or array

So the outer-most data type in a JSON text had to be either an object or an array, it couldn't be a string, boolean, number or any other data type.

Why does JSON.parse fail with the empty string?

As an empty string is not valid JSON it would be incorrect for JSON.parse('') to return null because "null" is valid JSON. e.g.

JSON.parse("null");

returns null. It would be a mistake for invalid JSON to also be parsed to null.

While an empty string is not valid JSON two quotes is valid JSON. This is an important distinction.

Which is to say a string that contains two quotes is not the same thing as an empty string.

JSON.parse('""');

will parse correctly, (returning an empty string). But

JSON.parse('');

will not.

Valid minimal JSON strings are

The empty object '{}'

The empty array '[]'

The string that is empty '""'

A number e.g. '123.4'

The boolean value true 'true'

The boolean value false 'false'

The null value 'null'

Can a single, stand-alone literal form a valid JSON document?

Found this on comment

Actually there are two different JSON specifications. RFC 4627 requires a JSON text to be an object or an array. ECMA-262, 5th edition, section 15.12 does not impose this restriction.

JSON root element



Related Topics



Leave a reply



Submit