Skip to content Skip to sidebar Skip to footer

Is '""' A Valid JSON String?

I am confused. To quote json.org JSON is built on two structures: A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary

Solution 1:

So, I don't think "" should be a valid JSON string

It is a valid JSON string (which is a data type that may appear in a JSON text).

as its neither a list values(i.e. does not start with '[' and ends with ']')

A JSON text (i.e. a complete JSON document) must (at the outermost level) be either an object or an array. A string is not a valid JSON text.

The formal specification says:

A JSON text is a serialized object or array.

But back to quoting the question here:

but JSON.parse doesn't give exception and returns empty string.

The JSON parser you are using is being overly-liberal. Don't assume that all JSON parsers will be.

For example, if I run perl -MJSON -E'say decode_json(q{""})' I get:

JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this) at -e line 1.


Solution 2:

No, '' is not valid JSON. JSON.parse('') does throw an error – just look in your browser console.

Next time you have an "is this valid JSON?" question, just run it through a JSON validator. That's why they exist.


Solution 3:

Following the newest JSON RFC 7159, "" is in fact valid JSON. But in some earlier standards it wasn't.

Quote:

A JSON text is a sequence of tokens. The set of tokens includes six structural characters, strings, numbers, and three literal names.

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.


Post a Comment for "Is '""' A Valid JSON String?"